2 回答
TA贡献1833条经验 获得超4个赞
您可以检查数组是否包含任何对象name = "All"。
那么,return true如果
数组有name = "All"对象,数组的长度是1
或者数组没有name = "All"
function checkObj(arr) {
const hasAll = arr.some(o => o.name === "All")
return (arr.length === 1 && hasAll) || !hasAll
}
这是一个片段:
function checkObj(arr) {
const hasAll = arr.some(o => o.name === "All")
return (arr.length === 1 && hasAll) || !hasAll
}
const obj1=[{id:1,name:"All",value:"all"},{id:2,name:"Sun",value:"sun"},{id:3,name:"Mon",value:"mon"},],
obj2=[{id:4,name:"Thur",value:"thur"},{id:8,name:"Mon",value:"mon"},],
obj3=[{id:1,name:"Thur",value:"thur"},{id:5,name:"All",value:"all"},{id:2,name:"Mon",value:"mon"},{id:6,name:"All",value:"all"}],
obj4=[{id:1,name:"All",value:"all"}];
console.log( checkObj(obj1) )
console.log( checkObj(obj2) )
console.log( checkObj(obj3) )
console.log( checkObj(obj4) )
TA贡献1785条经验 获得超4个赞
你可以Array#every
在计数超过一时短路。
function checkArray(array) {
return array.every((count => ({ name }) => (count += name === "All") < 2)(0));
}
var array1 = [{ id: 1, name: "All", value: "all" }, { id: 2, name: "Sun", value: "sun" }, { id: 3, name: "Mon", value: "mon" }],
array2 = [{ id: 4, name: "Thur", value: "thur" }, { id: 8, name: "Mon", value: "mon" }],
array3 = [{ id: 1, name: "Thur", value: "thur" }, { id: 5, name: "All", value: "all" }, { id: 2, name: "Mon", value: "mon" }, { id: 6, name: "All", value: "all" }];
console.log(checkArray(array1), checkArray(array2), checkArray(array3));
添加回答
举报