我有以下数组
// Exmaple
[
['morning', 'afternoon'],
['morning'],
['morning', 'afternoon'],
['morning', 'afternoon'],
['morning']
]
我可能有一个相同的人,但是每个阵列都有下午。
我需要检查所有数组中是否存在给定值,例如,如果我检查'morning',它应该返回true
,但是如果我检查'Afternoon'< / strong>,它应该返回false
,因为在上面的示例数组中,并非所有人都有'Afternoon'
答案 0 :(得分:5)
array.every(day => day.includes("morning")) // true
答案 1 :(得分:3)
您可以使用.every()
和.includes()
方法:
let data = [
['morning', 'afternoon'],
['morning'],
['morning', 'afternoon'],
['morning', 'afternoon'],
['morning']
];
let checker = (arr, str) => arr.every(a => a.includes(str));
console.log(checker(data, 'morning'));
console.log(checker(data, 'afternoon'));
答案 2 :(得分:2)
您可以使用Array.every和Array.includes
let arr = [['morning', 'afternoon'],['morning'],['morning', 'afternoon'],['morning', 'afternoon'],['morning']];
console.log(arr.every(v => v.includes('morning'))); // true
console.log(arr.every(v => v.includes('afternoon'))); // false
答案 3 :(得分:1)
use .every()
array.every(d => d.includes("morning")) // true
array.every(d => d.includes("afternoon")) //false
答案 4 :(得分:0)
您可以使用Array.prototype.every()并将Array.prototype.find()的结果强制转换为boolean
,该结果返回满足提供的测试功能的数组中第一个元素的值。否则返回undefined。
代码:
const data = [['morning', 'afternoon'],['morning'],['morning', 'afternoon'],['morning','afternoon'],['morning']];
const checker = (arr, str) => arr.every(a => !!a.find(a => str === a));
console.log(checker(data, 'morning'));
console.log(checker(data, 'afternoon'));