有許多的問題與你是如何調用方法和你來自哪裏,返回ACC:
function noDuplicates(arrays) {
var arrayed = Array.prototype.slice.call(arguments);
// reduce is a method of an array, so call it as a method
// return reduce(arrayed, function(acc, cur) {
return arrayed.reduce(function(acc, cur) {
// Same with forEach
cur.forEach(function(item) {
if (acc[item] === undefined) {
acc.push(item);
}
// Return acc from the reduce callback, forEach returns undefined always
// return acc;
});
return acc;
}, []);
}
console.log(noDuplicates([1, 2, 2, 4], [1, 1, 4, 5, 6]));
你也可以撥打直接減少上參數使用電話:
Array.prototype.reduce.call(arguments, function(acc, curr) {
// ...
});
以上,使你的代碼運行,但它不會產生正確的輸出作爲測試:
if (acc[item] === undefined)
你想要什麼沒有做。你需要做的是記住每個值,而只把它推到ACC如果它以前沒有見過:
function noDuplicates(arrays) {
var arrayed = Array.prototype.slice.call(arguments);
var seen = {};
return arrayed.reduce(function(acc, cur) {
cur.forEach(function(item) {
if (!seen[item]) {
acc.push(item);
seen[item] = true;
}
});
return acc;
}, []);
}
console.log(noDuplicates([1, 2, 2, 4], [1, 1, 4, 5, 6]));
一些其他的方法:
// A more concise version of the OP
function noDupes() {
return [].reduce.call(arguments, function(acc, arr) {
arr.forEach(function(value) {
if (acc.indexOf(value) == -1) acc.push(value);
});
return acc;
},[]);
}
console.log(noDupes([1, 2, 2, 4], [1, 1, 4, 5, 6]));
// Some ECMAScript 2017 goodness
function noDupes2(...args){
return [].concat(...args).filter((v, i, arr) => arr.indexOf(v)==i);
}
console.log(noDupes2([1, 2, 2, 4], [1, 1, 4, 5, 6]));
應該輸出什麼3210 console.log(noDuplicates([1,2,2,4],[1,1,4,5,6]));? – Ved
輸出應該是[1,2,4,5,6] – learninjs
[從JavaScript數組中刪除重複]的可能副本(http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array) –