gpt4 book ai didi

javascript - 删除特定参数

转载 作者:行者123 更新时间:2023-11-30 16:16:44 26 4
gpt4 key购买 nike

我试图根据传递的变量删除一些单词。

但是,我写的两个版本的代码略有不同!

它们导致了不同类型的输出,我不明白为什么!

所以我需要你们的帮助,非常感谢你们!

This function will be accepting the different numbers of variables,

which might be ( [arr],1,2 ) or ( [arr],1,2,8,9...) etc,

and remove the the variable in the first array according to the passing numbers.

For example: destroyer ( [1, 2, 3, 4], 2, 3 ) --> output should be [1,4]

And here is my code. ( Notice the minor difference with bold fonts! )

function destroyer(arr) {
for ( var i = 1; i < arguments.length; i++ ){
arr = arguments[0].filter(function(value){
if( value == arguments[i]){
return false;
}else{
return true;
}
});
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

The output will be [1,2,3,1,2,3], which means value == arguments[i] doesn't work. However,

function destroyer(arr) {
for ( var i = 1; i < arguments.length; i++ ){
filter = arguments[i];
arr = arguments[0].filter(function(value){
if( value == filter){
return false;
}else{
return true;
}
});
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

This version works perfectly showing me [1,1].

So what's going wrong with the first version??? Thank you!!

最佳答案

第一个的问题是 arguments 适用于 .filter() 回调函数(最近的函数作用域,而不是父函数作用域)所以 arguments[i] 不是您想要的。

您可以将这些参数复制到一个实际的数组中,然后您可以从 .filter() 回调中引用它。

function destroyer(arr) {
var args = [].slice.call(arguments, 1);
for ( var i = 0; i < args.length; i++ ){
arr = arr.filter(function(value){
if( value == args[i]){
return false;
}else{
return true;
}
});
}
return arr;
}
var a = destroyer([1, 2, 3, 1, 2, 3], 2, 3);

// show output
document.write(JSON.stringify(a));


就我个人而言,我建议使用更简单的版本:

function destroyer(arr) {
var args = [].slice.call(arguments, 1);
return arr.filter(function(value) {
return args.indexOf(value) === -1;
});
}
var a = destroyer([1, 2, 3, 1, 2, 3], 2, 3);

// show output
document.write(JSON.stringify(a));


其中,在 ES6 中可以使用扩展运算符编写得更简单:

function destroyer(arr, ...args) {
return arr.filter(function(value) {
return args.indexOf(value) === -1;
});
}
var a = destroyer([1, 2, 3, 1, 2, 3], 2, 3);

// show output
document.write(JSON.stringify(a));


或者,如果您更喜欢更短的 ES6 符号并希望使用新的 Array.prototype.includes():

function destroyer(arr, ...args) {
return arr.filter(value => !args.includes(value));
}
var a = destroyer([1, 2, 3, 1, 2, 3], 2, 3);

document.write(JSON.stringify(a));

关于javascript - 删除特定参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com