Javascript:从数组中删除特定项目并返回没有这些项目的原始数组

凯蒂雷诺兹

JS 新手。做一个练习,我想从数组中删除一些特定的项目,并在没有这些项目的情况下返回原始数组。我以一种方式做到了,但示例解决方案完全不同,我想尝试并理解它。

我的思路是否正确(请参阅下面每行代码后的注释)?我想我明白了,但我不确定我的推理是正确的还是我运气好。我想确保下次我看到这样的事情时我完全理解。

const pull = (arr, ...args) => {
        // In this case, arr = arra1 and ...args = the values "a" and "c"
    let argState = Array.isArray(args[0]) ? args[0] : args;     
        // I think this is saying, "Is the first item (index[0]) in arra1 included in the list of the arguments that follow (in this case, "a" and "c")?"
        // The value of arra1[0] is "a", which is indeed one of the arguments that follow, so the ternary operator would return false and give you the "args", which are "a" and "c" in this case.
        // "a" and "c" form an array (do they? I may be wrong here), so Array.isArray() would evaluate to true, and therefore argState = true
    let pulled = arr.filter((v, i) => !argState.includes(v));
        // I think this is saying, "Loop through arra1. v is the first value, "a" in this case. "Does argState contain the value "a"? 
        // It does, so it will come back true which will evaluate to false when we apply the "!". So "a" is NOT filtered into the new array called "pulled". 
        // Second loop, does argState contain the value "b"? It does not, so it will come back false, which will evaluate to true when we apply the "!". So "b" IS filtered into the new array called "pulled". 
        // And so on and so forth, and we would end up with "pulled = [ b , b ]" for this line.
    arr.length = 0;
        // I believe this just empties the original arr, or arra1 in this case. So arra1 = [ ]
    pulled.forEach(v => arr.push(v));
        // Now we loop through "pulled" and push each value onto arra1
    return pulled;
        // This will return the original arra1 with the new values [ b, b ]
  };

let arra1 = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(pull(arra1, 'a', 'c')); // will return ["b","b"]

我的主要困惑源于!argState.includes(v)部分。如果argState在我们前行结束了的值true或者false,它没有任何意义,我认为我们可以检查是否argState包括值(v)arra1阵列(即“A”,“B”,或者在这个练习中的“C”) . argState当它已经设置为值truefalse因为 Array.IsArray() 检查时,如何包含这样的值

某些表演

当 argState 由于 Array.IsArray() 检查而仅设置为 true 或 false 值时,它如何包含这样的值?

它没有设置为truefalse它被设置为一个数组:

let argState = Array.isArray(args[0]) ? args[0] : args;   

如果args[0]是数组,则将其设置为该数组。否则,它被设置为整个args数组。

这相当于

let argState;
if (Array.isArray(args[0])) {
  argState = args[0];
} else {
  argState = args;
}

这允许调用者使用任一格式

pull(someArr, ['foo', 'bar'])

pull(someArr, 'foo', 'bar')

并且使用条件运算符来构造argState然后收集一个数组,['foo', 'bar']而不管调用者使用什么格式。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章