问题
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