根据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
}
答案 0 :(得分:3)
使用delete test[prop]
代替delete test.prop
,因为在第二种方法中,您试图从字面上删除属性prop
(您的对象中没有)。此外,默认情况下,如果对象的值为null
,undefined
,""
,false
,0
,NaN
在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);