JavaScript:将方法添加到Array.prototype对象以从输入数组中排除索引值 [英] JavaScript: Add Method to Array.prototype Object to Exclude Index Values from an Input Array

查看:57
本文介绍了JavaScript:将方法添加到Array.prototype对象以从输入数组中排除索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写将doNotInclude方法添加到Array.prototype对象的代码.

I want to write code that adds the doNotInclude method to the Array.prototype object.

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

The purpose of my code is: does not include the index values from the array passed to 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])

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

My code executes successfully and returns:

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

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

My question is what is the following line of code doing?

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

在我的示例中,将其注释掉似乎不会影响输出,因此我很好奇在什么情况下需要该行代码?

In my example, commenting it out does not appear to impact the output, so I'm curious in what situations would I need that line of code?

推荐答案

代码 if(!Array.isArray(arr))arr = [arr]; 只是一种保护措施.它将参数 arr 转换为数组(如果还不存在的话).换句话说,这段代码实现了以下行为:

The code if (!Array.isArray(arr)) arr = [arr]; is just a safeguard. It converts the argument arr into an array, if it's not already one. In other words, that piece of code enables the following behavior:

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

如果没有这种保护措施,上面的代码将完全失败.示例:

Whereas without that safeguard, the above code would simply fail. Example:

// 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

这篇关于JavaScript:将方法添加到Array.prototype对象以从输入数组中排除索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆