【问题标题】:How to delete object property?如何删除对象属性?
【发布时间】:2015-02-17 21:43:19
【问题描述】:

根据docs,删除操作符应该能够从对象中删除属性。我正在尝试删除“虚假”对象的属性。

例如,我假设以下内容会从 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 
}

【问题讨论】:

    标签: javascript object properties boolean


    【解决方案1】:

    使用delete test[prop] 而不是delete test.prop,因为使用第二种方法,您试图从字面上删除属性prop(您的对象中没有该属性)。同样默认情况下,如果对象的值为null,undefined,"",false,0,NaN 在 if 表达式中使用或返回 false,因此您可以更改您的 @987654330 @函数到

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

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 2020-02-21
      • 2017-06-02
      • 2015-03-10
      相关资源
      最近更新 更多