检查一个数组中至少有一个值是否存在在另一个数组中是否存在失败



以下应返回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中是否至少存在一个值。

相反的情况也是错误的:

console.log(array2.some(v => modified.includes(v))); //false should be true

jsfiddle

问题在此行中:

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

array2.splice(index, 1);修改了您的array2,因此不再包含Fred!使用slice代替splice

另请参见:https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/slice

与:https://developer.mozilla.org/en-us/docs/web/javascript/Reference/global_objects/array/splice

将确定为1。 array2.splice(index, 1);将从array2中删除'fred'。当您是:

console.log(modified.some(v => array2.cludes(v)));

array2实际上是['sue'],而修改为['fred']。

因此评估为错误。

您应该使用Array.prototype.slice() 如果您不想修改array2

,而不是Array.prototype.splice()

最新更新