For Ex : original array : a =[1,2,3,4,g,5]
if the user wrongly entered the above array like this : a = [2,1,3,4,g,5]
如何使用javascript?從原始數組列表中找到位置改變的元素(即[1,2]已被更改)。如何使用javascript在數組中查找更改順序的內容?
For Ex : original array : a =[1,2,3,4,g,5]
if the user wrongly entered the above array like this : a = [2,1,3,4,g,5]
如何使用javascript?從原始數組列表中找到位置改變的元素(即[1,2]已被更改)。如何使用javascript在數組中查找更改順序的內容?
// 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 + '\'.');
}
});
試試這個
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);
如果你有兩個數組相同大小:
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
數組包含你想要的結果。
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);
您應該使用'!=='而不是'!='。 – 2014-12-02 09:12:40
是的,'!=='更安全,謝謝 – Girish 2014-12-02 09:15:09
很酷的東西..寶貝謝謝 – jswoody 2014-12-02 09:52:23