问题
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".
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
}
回答1:
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;
}
Try with this code:
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);
来源:https://stackoverflow.com/questions/28571651/how-to-delete-object-property