如何删除JavaScript对象中undefined或nullJavaScript对象中的所有属性?
undefined
null
(问题与此数组类似)
您可以遍历对象:
var test = { test1 : null, test2 : 'somestring', test3 : 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } } clean(test);
如果您担心此属性删除不会使对象的proptype链运行起来,则还可以:
function clean(obj) { var propNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } }
有关null与未定义的一些注意事项:
test.test1 === null; // true test.test1 == null; // true test.notaprop === null; // false test.notaprop == null; // true test.notaprop === undefined; // true test.notaprop == undefined; // true