JavaScript: Add Method to Array.prototype Object to Exclude Index Values from an Input Array

折月煮酒 提交于 2021-02-11 12:12:01

问题


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

The purpose of my code is: does not include the index values from the array passed to doNotInclude.

Code below:

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?


回答1:


Basically it's checking to see if your input is an array, and if not, it makes it into a single element array.

This is because the logic of the code requires the input to be an array since it uses Array.includes(). This line will never execute if your input is always an array, so it's not technically necessary, but it would allow you to pass

1

as well as

[1]

and not get an error.




回答2:


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


来源:https://stackoverflow.com/questions/57067019/javascript-add-method-to-array-prototype-object-to-exclude-index-values-from-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!