如何删除使用从参数数组元素对象 - 这有什么错我的code?
我试图从上一个函数作为参数传递的数组删除元素。我想从数组中删除的元素是那些相同功能的以下参数。像这样:驱逐舰([1,2,3,1,2,3,2,3);
因此,如果阵列(驱逐舰的第一个参数)中含有2 和3,我希望他们删除。因此,调用函数应该返回[1,1]。
I am trying to remove elements from an array that is passed on a function as an argument. The elements that I am trying to remove from the array are the ones equal to the following arguments of the function. Like this: destroyer([1, 2, 3, 1, 2, 3], 2, 3);
so if the array (first argument of destroyer) contains "2" and "3", I want them removed. So calling the function should return [1, 1].
function destroyer(arr) {
var args = [];
for(var j = 1; j<arguments.length; j++){
args.push(arguments[j]);
for(var i = 0; i<arr.length; i++){
if(args.indexOf(arr[i]) > -1){
arr.splice(i, 1)
}
}
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
我不明白为什么我的code适用于驱逐舰([1,2,3,1,2,3,2,3);
(它返回[1,1]),但不用于破坏者([2,3,2,3],2,3);
(它应该返回[],但返回[3])。
I don't understand why my code works for destroyer([1, 2, 3, 1, 2, 3], 2, 3);
(it returns [1, 1]) but not for destroyer([2, 3, 2, 3], 2, 3);
(it should return [], but returns [3]).
请帮我明白为什么这是行不通的。
Please, help me understand why this doesn't work.
在privous答案是正确的,
但我得到的东西的工作,它更类似问题的code,使他明白了:
code:
the privous answer is right, but i got something working , it's more similar to the question's code, help him to understand: code:
function destroyer(arr) {
var args = [];
//You want add all the nums you want remove from array, so you start from 1, which means second arg,first arg is the array you want to perform
for(var j = 1; j<arguments.length; j++){
//You store the args to an arg array
args.push(arguments[j]);
//Once you have the arg, you want loop the target array, see if the newly added arg exist in the target array, if it is, then remove it
for(var i = 0; i<arr.length; i++){
//Found it, remove it now! note: your found the index, then you need take it out, check the doc for slice function arr.slice([begin[, end]]) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
if(args.indexOf(arr[i]) > -1){
//key change, remove the element
arr.splice(i, i+1)
}
}
}
return arr;
}
destroyer([2, 3, 2, 3], 2, 3);
`
此外,已为您创建一个播放
Also, have created a play for you
例如:片(1,4)中提取所述第二元件到第四元件(元素索引1,2,和3)
example: slice(1,4) extracts the second element up to the fourth element (elements indexed 1, 2, and 3).