【问题标题】:JS: Create a method to return an array that does not include the index values from the array passed to my methodJS:创建一个方法来返回一个数组,该数组不包括传递给我的方法的数组中的索引值
【发布时间】:2019-10-19 09:01:26
【问题描述】:

我正在尝试创建一个添加到 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; 
      }
    })
  }

我的代码没有通过任何规范。我究竟做错了什么?

还要检查我的概念理解,过滤方法是在哪个数组上运行的?它是包含索引的那个吗?

【问题讨论】:

  • 您想要一个方法,它采用给定的数组并删除与第二个参数中的数组值匹配的值?

标签: javascript arrays object methods filter


【解决方案1】:

我假设您需要一种方法,该方法采用给定数组并删除与作为参数传递的数组的值匹配的值。此演示将返回值与传入数组的值不匹配的数组索引。这可以通过最新的数组方法.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));

【讨论】:

  • 谢谢;这行代码是做什么的?返回 array.includes(value) ? [] : [索引];
【解决方案2】:

1) 你不想 return elem 想要返回一个布尔值,指示是否应该包含 elem

2) doNotInclude(3) 表示arr 可能不是一个数组。您必须使用Array.isArray(arr) 进行检查并相应地更改逻辑(直接将索引与arr 进行比较)。

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多