我有这个数组,它是用户生成的,并随着时间的推移而变化:
const data = [["2020-09-14","15:00","60","Info","April Tucker","Other","yes"],
["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]]用户选择保存到sessionStorage的日期(例如: 2020-11-21):sessionStorage.getItem('date')
然后我使用forEach方法来了解数组项的第一项是否具有相同的值:
const checkForConflicts = () => {
mydata.forEach((element) => {
element.includes(sessionStorage.getItem('date'))
})
}如果我通过控制台记录,我会得到数组中所有项布尔值。如何仅返回一个布尔值,如果checkForConflict仅返回false值,则为true;如果返回alt至少一个TRUE值,则返回false值。
发布于 2020-09-11 04:18:44
这可能是Array.prototype.every或Array.prototype.some中的一种,甚至两者都会为您带来手头上的正确工具。
..。简化的示例代码...
const data = [
["2020-09-14","15:00","60","Info","April Tucker","Other","yes"],
["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]
];
console.log(
'data.every(item => item[0] === "2020-09-14") ? ',
data.every(item => item[0] === "2020-09-14")
);
console.log(
'data.some(item => item[0] === "2020-09-14") ? ',
data.some(item => item[0] === "2020-09-14")
);
data.push(
["2020-09-15","2:00","50","Text","April Tucker","Other","yes"]
);
console.log(
'data.every(item => item[0] === "2020-09-14") ? ',
data.every(item => item[0] === "2020-09-14")
);
console.log(
'data.some(item => item[0] === "2020-09-14") ? ',
data.some(item => item[0] === "2020-09-14")
);.as-console-wrapper { min-height: 100%!important; top: 0; }
发布于 2020-09-11 02:50:29
尝试使用some()方法:
const checkForConflicts = () => {
mydata.forEach((element) => {
element.some(!sessionStorage.getItem('date'))
})
}
发布于 2020-09-11 02:54:53
不需要在数据上使用forEach和循环,只需对冲突项使用-1 \f25 findIndex -1表示它们没有冲突
const checkForConflicts = () => {
return data.findIndex((element) => {
element.includes(sessionStorage.getItem('date'))
}) !== -1;
}最重要的是,你必须在函数中返回值。
https://stackoverflow.com/questions/63835922
复制相似问题