以下内容应返回 true,但报告为 false:
var array1 = ['fred'];
var array2 = ['sue', 'fred'];
var modified = [];
//create a new modified array that converts initials to names and vice versa
array1.forEach(function(element) {
var index = array2.findIndex(el => el.startsWith(element[0]));
if (index > -1) {
modified.push(array2[index]);
array2.splice(index, 1);
} else {
modified.push(element);
}
});
console.log(modified); // should be the same as array1
console.log(modified.some(v => array2.includes(v))); //false should be true
我正在尝试检查 array2 中是否至少存在一个modified值。
相反也是错误的:
console.log(array2.some(v => modified.includes(v))); //false should be true
最佳答案
问题出在这一行:
array2.splice(index, 1);
您实际上是从 array2
中删除找到的项目,所以当然,如果您稍后在 array2
中查找该项目,它就会获胜不会被发现。观察:
var array1 = ['fred'];
var array2 = ['sue', 'fred'];
var modified = [];
//create a new modified array that converts initials to names and vice versa
array1.forEach(function(element) {
var index = array2.findIndex(el => el.startsWith(element[0]));
if (index > -1) {
modified.push(array2[index]);
array2.splice(index, 1);
} else {
modified.push(element);
}
});
console.log("modified: ", ...modified); // should be the same as array1
console.log("array2: ", ...array2); // array2 has been modified
一个快速解决方案是在开始修改数组 array2
之前对其进行克隆,然后在克隆上进行工作:
var array1 = ['fred'];
var array2 = ['sue', 'fred'];
var modified = [];
var filtered = [...array2];
//create a new modified array that converts initials to names and vice versa
array1.forEach(function(element) {
var index = filtered.findIndex(el => el.startsWith(element[0]));
if (index > -1) {
modified.push(array2[index]);
filtered.splice(index, 1);
} else {
modified.push(element);
}
});
console.log(modified.some(v => array2.includes(v))); // true
关于javascript - 检查一个数组中的至少一个值是否存在于另一个数组中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172343/