【发布时间】: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