如何删除对象属性?

How to delete object property?

根据 docs 删除运算符应该能够从对象中删除属性。我正在尝试删除 "falsey".

对象的属性

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

    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 
}

使用 delete test[prop] 而不是 delete test.prop 因为使用第二种方法你试图从字面上删除 属性 prop (你的对象中没有).同样默认情况下,如果对象的值为 nullundefined""false0NaN,则在 if 中使用表达式或 returns 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);