簡體   English   中英

如何刪除對象屬性?

[英]How to delete object property?

根據文檔 ,delete操作符應該能夠從對象中刪除屬性。 我正在嘗試刪除“ 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 
}

使用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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM