2015-11-20 101 views
1

索引我有兩個數組獲取元素的差異陣列

var valid = ["a", "b"]; 
var different = ["a", "c", "b"]; 

什麼是找出元素不同的位置,最好的方法?只有一個元素可以不同。

在這種情況下,不同的數組只改變一個元素,我希望不同數組的索引()。

+0

循環和索引?或循環和比較?多種方式。 – epascarello

+0

我需要在第二個數組中不同的元素索引(在這種情況下命名爲不同) – Davide

回答

1

有多種方法可以做到這一點。例如,您可以遍歷valid數組,當數值不匹配時,則知道index的不同值。在這種情況下,它是1

Example Here

var valid = ["a", "b"]; 
var different = ["a", "c", "b"]; 

valid.forEach(function (value, i) { 
    if (value !== different[i]) { 
    console.log(i); // 1 
    } 
}); 
+0

我需要它沒有forEach,因爲是異步的,我不能退出循環 – Davide

0

返回不同值的索引:

var valid = ['a', 'b']; 
 
var different = ['a', 'c', 'b']; 
 

 
var diffIndex = valid.findIndex(function (value, index) { 
 
    return value !== different[index]; 
 
}); 
 

 
alert('Array differs at index: ' + diffIndex);

注意findIndex是ES2015標準的一部分。