3 回答
TA贡献1798条经验 获得超3个赞
您可以转换为 boolean ( !el.id) 这将处理大多数情况,您必须"undefined"单独处理:
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
var obj1 = {};
var prop1 = [];
var prop2 = [];
arr.forEach(el=>{
if(!el.id || el.id === "undefined"){
prop1.push(el)
}
else{
prop2.push(el)
}
})
console.log(prop1);
console.log(prop2);
console.log(prop1.length);
console.log(prop2.length);
TA贡献1789条经验 获得超8个赞
尝试这个:
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
let filterArray = arr.filter((el) => {return !el.id || [0,null,"undefined",NaN].includes(el.id)});
console.log(filterArray);
let filterArray1 = arr.filter((el) => {return el.id && ![0,null,"undefined",NaN].includes(el.id)});
console.log(filterArray1);
TA贡献1772条经验 获得超5个赞
为什么它不起作用?是顺序不正确还是有 JavaScript 错误?
代码乍一看很好,您可以使用 if (!el.id),它检查 id 是否为“假”(0,null,undefined,NaN,false)
您还可以查看“map”和“filter”方法, https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map
添加回答
举报