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

时间:2019-03-14 21:32:43

标签: javascript arrays

以下内容应返回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

3 个答案:

答案 0 :(得分:1)

问题出在这一行:

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

答案 1 :(得分:0)

答案 2 :(得分:0)

因为索引将被确定为1。array2.splice(index, 1);将删除array2中的'fred'。以及您何时:

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

array2实际上是['sue'],修改后的是['fred']。

因此计算为假。

您应该使用Array.prototype.slice()  如果您不想修改array2,则可以使用Array.prototype.splice()