0
根據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
}