如何删除对象属性?

时间:2015-02-17 21:43:20

标签: javascript object properties boolean

根据docs,删除操作符应该能够从对象中删除属性。我试图删除" falsey"。

的对象的属性

例如,我假设以下内容将从testObj中删除所有falsey属性,但它不会:

    var test = {
        Normal: "some string",  // Not falsey, so should not be deleted
        False: false,
        Zero: 0,
        EmptyString: "",
        Null : null,
        Undef: undefined,
        NAN: NaN                // Is NaN considered to be falsey?
    };

    function isFalsey(param) {
        if (param == false ||
            param == 0     ||
            param == ""    ||
            param == null  ||
            param == NaN   ||
            param == undefined) {
            return true;
        }
        else {
            return false;
        }
    }

// Attempt to delete all falsey properties
for (var prop in test) {
    if (isFalsey(test[prop])) {
        delete test.prop;
    }
}

console.log(test);

// Console output:
{ Normal: 'some string',
  False: false,
  Zero: 0,
  EmptyString: '',
  Null: null,
  Undef: undefined,
  NAN: NaN 
}

1 个答案:

答案 0 :(得分:3)

使用delete test[prop]代替delete test.prop,因为在第二种方法中,您试图从字面上删除属性prop(您的对象中没有)。此外,默认情况下,如果对象的值为nullundefined""false0NaN在if中使用表达式或返回false,因此您可以将isFalsey函数更改为

 function isFalsey(param) {
     return !param;
 }

尝试使用此代码:

var test = {
        Normal: "some string",  // Not falsey, so should not be deleted
        False: false,
        Zero: 0,
        EmptyString: "",
        Null : null,
        Undef: undefined,
        NAN: NaN                // Is NaN considered to be falsey?
    };

    function isFalsey(param) {
        return !param;
    }

// Attempt to delete all falsey properties
for (var prop in test) {
    if (isFalsey(test[prop])) {
        delete test[prop];
    }
}

console.log(test);