2015-02-17 111 views
0

根据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 
} 

回答

3

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