实施例
var array1=['1','2','3','4'];
var array2=['1,2,3,4,5','1,2,3,6','1,7,8,9'];
比较这两个数组。
我试试这段代码:
for (var i = 0; i < array1.length; i++) {
for (var j= 0; j< array2.length; j++) {
if()
--------
}
}
先谢谢
答案 0 :(得分:2)
您可以使用array1
的拆分项的任意值检查array2
的每个值。
ES5
var array1 = ['1', '2', '3', '4'],
array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'],
check = array2.some(function (c) {
return array1.every(function (b) {
return function (a, i) {
return a === b[i];
};
}(c.split(',')));
});
console.log(check);
&#13;
ES6
var array1 = ['1', '2', '3', '4'],
array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'],
check = array2.some(c => array1.every((b => (a, i) => a === b[i])(c.split(','))));
console.log(check);
&#13;
答案 1 :(得分:1)
尝试使用join(',')
和includes()
方法。
已更新
返回匹配的参数
使用Array#reduce
帮助匹配每个array1
参数
var array1 = ['1','2', '4'];
var array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'];
var res = array2.reduce(function(a, b) {
array1.forEach(function(val) {
if (b.includes(val) && !a.includes(b)) {
a.push(b);
}
})
return a;
}, [])
console.log(res);
console.log(res.length > 0)
&#13;