Seek and Destroy
摧毀數(shù)組
金克斯的迫擊炮!
實現(xiàn)一個摧毀(destroyer)函數(shù),第一個參數(shù)是待摧毀的數(shù)組,其余的參數(shù)是待摧毀的值。
第一種解法:
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轉(zhuǎn)化為一個數(shù)組,1是slice()方法里面的起始下標(biāo)
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)