在以下情况下,我想检测数组1中的值是否与array2相同:
var array1 = ["Bob","Jason","Fred"];
var array2 = ["Bob","Fred"]; // result: true,expected: true
or
var array1 = ["Bob","Fred","Jason"]; // result: false,expected: False
or
var array1 = ["Bob","Jason"]; // result: true,expected: True
or
var array1 = ["Jason","Bob"];
var array2 = ["Bob","Jason"]; // result: false,expected: False
or
var array1 = ["Jason","Bob"];
var array2 = ["Jason","Sue","Bob"]; // result: false,expected: True - just because array 2 contains sue and array 1 doesn't,doesn't mean jason and bob aren't in the right order. They are. We need to ignore the fact sue is interrupting them.
or
var array1 = ["Jason","Bob","Sue"]; // result: false,expected: False
or
var array1 = ["Sue","Sue"];
var array2 = ["Jason",expected: True - just because jason is playing third wheel doesn't mean bob and sue aren't in the correct order. they are. we need to ignore jason.
or
var array1 = ["Bob","Bob"]; // result: true,expected: true
or
var array1 = ["Bob","Bob"];
var array2 = ["Sue",expected: true - in this scenario,we have two Bobs. while Bob followed by Sue is false,sue followed by bob is true. we need to ignore the first Bob.
到目前为止,我已经明白了这一点:
if (array1.length > array2.length) {
var arrayLength = array1.length;
} else if (array1.length < array2.length) {
var arrayLength = array2.length;
} else {
var arrayLength = array1.length;
}
for (var i = 0; i < arrayLength; i++){
if (array1[i] !== array2[i]) {
return false;
} else {
return true;
}
}
我的问题是上述方法并非始终都能产生预期的结果.即,如果两个数组的长度相同,那么我得到了预期的结果,但是如果不是,则没有得到预期的结果.
最佳答案
myArray是一个坏名字,因为它不是数组.它是两个数组共享的最小长度,因此将其命名为minLength左右.然后,您可以对所有索引进行索引,直到i达到minLength,但minLength [i]没有意义.相反,您想在数组中查找,例如array1 [i]和array2 [i]并比较结果(带有===).
有了这些信息,您应该能够以自己的方式解决它:)
我该怎么做:
const result = array1.every((el,i) => i >= array2.length || el === array2[i]);