代码之家  ›  专栏  ›  技术社区  ›  PineNuts0

JavaScript:将方法添加到数组中。prototype对象从输入数组中排除索引值

  •  0
  • PineNuts0  · 技术社区  · 7 年前

    我想编写代码,将doNotInclude方法添加到数组中。原型对象。

    我的代码的目的是:不包括传递给的数组中的索引值 doNotInclude .

    代码如下:

    Array.prototype.doNotInclude = function (arr) {
      //if (!Array.isArray(arr)) arr = [arr];
      return this.filter((val, i) => {
        if (!arr.includes(i)) return val;
      });
    };
    
    ['zero', 'one', 'two', 'three', 'four', 'five', 'six'].doNotInclude([0, 1])
    

    我的代码成功执行并返回:

    [ 'two', 'three', 'four', 'five', 'six' ]
    

    我的问题是下面这行代码在做什么?

    //if (!Array.isArray(arr)) arr = [arr];
    

    在我的例子中,注释掉它似乎不会影响输出,所以我很好奇在什么情况下需要这行代码?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Liftoff    7 年前

    基本上,它是检查你的输入是否是一个数组,如果不是,它会把它变成一个单元素数组。

    这是因为代码的逻辑要求输入是一个数组,因为它使用 Array.includes() .如果您的输入总是一个数组,那么这一行永远不会执行,所以从技术上讲这是不必要的,但它允许您通过

    1
    

    以及

    [1]
    

    而且不会出错。

        2
  •  0
  •   Alex Lomia    7 年前

    密码 if (!Array.isArray(arr)) arr = [arr]; 这只是一种保障。它改变了论点 arr 如果不是一个数组的话。换句话说,这段代码支持以下行为:

    ['zero', 'one', 'two'].doNotInclude(0) // Notice that the number is passed
    

    然而,如果没有这种保护措施,上述代码就会失败。例子:

    // 1. With safeguard
    Array.prototype.doNotInclude = function (arr) {
      if (!Array.isArray(arr)) arr = [arr];
      return this.filter((val, i) => {
        if (!arr.includes(i)) return val;
      });
    };
    
    console.log(['zero', 'one', 'two'].doNotInclude(0)); // executes normally
    
    // 2. Without safeguard
    Array.prototype.doNotInclude = function (arr) {
      //if (!Array.isArray(arr)) arr = [arr];
      return this.filter((val, i) => {
        if (!arr.includes(i)) return val;
      });
    };
    
    console.log(['zero', 'one', 'two'].doNotInclude(0)); // fails
    推荐文章