Seek and Destroy
摧毀數組
金克斯的迫擊炮!
實現一個摧毀(destroyer)函數,第一個參數是待摧毀的數組,其余的參數是待摧毀的值。
第一種解法:
function destroyer(arr){
var args=Array.prototype.slice.call(arguments,1);
var a=arr.filter(function(item,index,array){
return args.indexOf(item)==-1;//運用array.filter()方法最后要返回布爾值
})
console.log(a);
}
destroyer([1, 2, 3, 1, 2, 3], 2,3)
第二種解法:
function destroyer(arr){
var args=Array.prototype.slice.call(arguments,1);//Array.prototype.slice.call()是把argument轉化為一個數組,1是slice()方法里面的起始下標
var a=arr.filter(function(val){
for (var i=0;i<args.length;i++){
if(val==args[i]){
return false;
}
}
return true;//注意等for循環(huán)遍歷完了之后再返回
})
console.log(a);
}
destroyer([1, 2, 3, 1, 2, 3], 2,3)