我正在尝试创建一个添加到 Array.prototype 对象的方法。目标是返回一个数组,该数组不包含传递给我的方法的数组中的索引值。
以下是我的测试规范。
describe('doNotInclude', () => {
it('the doNotInclude method is added to the Array.prototype object', () => {
expect(typeof Array.prototype.doNotInclude).toBe('function');
});
it('returns an array', () => {
expect(Array.isArray([1, 2, 3, 4].doNotInclude(3))).toBe(true);
expect(Array.isArray([1, 2, 3, 4].doNotInclude([0, 2]))).toBe(true);
});
it('does not include the index values from the array passed to `doNotInclude`', () => {
expect([1, 2, 3, 4, 5].doNotInclude([3, 4])).toEqual([1, 2, 3]);
expect(
['zero', 'one', 'two', 'three', 'four', 'five', 'six'].doNotInclude([
0,
1,
])
).toEqual(['two', 'three', 'four', 'five', 'six']);
我的代码如下:
Array.prototype.doNotInclude = function (arr){
return this.filter((elem, index) => {
if (!arr.includes(index)){
return elem;
}
})
}
我的代码没有通过任何规范。我究竟做错了什么?
还要检查我的概念理解,过滤器方法在哪个数组上运行?它是包含索引的那个吗?
最佳答案
我假设您需要一个方法,该方法采用给定数组并删除与作为参数传递的数组值匹配的值。该演示将返回值与传入数组的值不匹配的数组索引。这可以通过最新的数组方法 .flatMap()
实现,它本质上是 .map( )
和 .flat()
方法相结合。映射部分将对每个值运行一个函数,就像 .map()
所做的一样,但不同之处在于每个返回都是一个数组:
array.map(function(x) { return x});
array.flatMap(function(x) { return [x]});
如果你想删除一个值,你返回一个空数组:
array.map(function(x) { return x}).filter(function(x) { return x !== z});
array.flatMap(function(x) { return x !== z ? [x] : []});
通过使用三元控件,您可以直接删除值,而不是通过 .filter()
间接删除。
if x does not equal z return [x] else return empty array []
return x !== z ? [x] : []
然后将结果展平为普通数组。
Array.prototype.exclude = function(array) {
return this.flatMap((value, index) => {
return array.includes(value) ? [] : [index];
})
}
let x = [1, 2, 3, 4, 5, 6, 7];
let z = x.exclude([3, 4]);
console.log(JSON.stringify(z));
关于javascript - JS : Create a method to return an array that does not include the index values from the array passed to my method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56433584/