2015-02-17 136 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);