如何删除对象属性? [英] How to delete object property?

查看:368
本文介绍了如何删除对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 docs 删除操作员应该能够从对象中删除属性.我正在尝试删除"falsey"对象的属性.

According to the docs the delete operator should be able to delete properties from objects. I am trying to delete properties of an object that are "falsey".

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

For example, I assumed the following would remove all of the falsey properties from testObj but it does not:

    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(在您的对象).同样默认情况下,如果对象在if表达式中使用nullundefined""false0NaN值或返回false,则可以更改功能

Use delete test[prop] instead of delete test.prop because with the second approach you are trying to delete the property prop literally (which you doesn't have in your object). Also by default if a object has a value which is null,undefined,"",false,0,NaN using in a if expression or returns false, so you can change your isFalsey function to

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

这篇关于如何删除对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆