2014-12-02 48 views

回答

2
// Try entering this at the prompt: [2, 1, 3, 4, 'g', 5] 

var original = [1, 2, 3, 4, 'g', 5], 
    input = eval(prompt('Enter an array please.')); 

input.forEach(function (element, index) { 
    var expected = original[index]; 
    if (element !== expected) { 
     // They are different. 
     // Logic to handle the difference goes here. Example: 
     console.log('Elements were different; ' + 
        'expected `' + expected + '\', ' + 
        'got `' + element + '\'.'); 
    } 
}); 
2

試試這個

var a = [1, 2, 3, 4, "g", 5]; 
var b = [2, 1, 3, 4, "g", 5]; 
var c = []; 
a.forEach(function(v, i){ 
    if(v !== b[i]) 
    c.push(v); 
}); 
console.log(c); 
+0

您應該使用'!=='而不是'!='。 – 2014-12-02 09:12:40

+0

是的,'!=='更安全,謝謝 – Girish 2014-12-02 09:15:09

+0

很酷的東西..寶貝謝謝 – jswoody 2014-12-02 09:52:23

2

如果你有兩個數組相同大小:

var a1 = [1, 2, 3, 4, 5]; 
var a2 = [2, 1, 3, 4, 5]; 
var diff = []; 

for(var i = 0, l = a1.length; i < l; i++) { 
    if (a1[i] !== a2[i]) { 
     diff.push(a1[i]); 
    } 
} 

而且diff數組包含你想要的結果。

1
var a1 = [1, 2, 3, 4, 5]; 
var a2 = [2, 1, 3, 4, 5]; 
var c=[]; 
a1.map(function(num,i){ 

      if(num !==a2[i]){ 
       c.push(num); 
      } 
}) 
console.log(c);