【问题标题】:How to Do array.map between two numbers [duplicate]如何在两个数字之间做array.map [重复]
【发布时间】:2019-12-03 09:28:28
【问题描述】:

假设我有数组

arr=[1,2,3,4,5,6,7,8,9,10]

所以我想基于两个值进行迭代,一个是索引和偏移量 ,例如,index=2offet=5 预期输出

newArray=[3,4,5,6,7]

我试过 .slice 但不符合要求

【问题讨论】:

  • arr.slice(2, 6).map((element, index)=>console.log(element, index)})

标签: javascript arrays ecmascript-6 array.prototype.map


【解决方案1】:

使用slice()

arr.slice([begin[, end]])

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let index = 2, offset = 5

console.log(arr.slice(index, index + offset))

使用splice()

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let index = 2, offset = 5

console.log(Array.from(arr).splice(index, offset))

【讨论】:

    【解决方案2】:

    您可以像这样slice() 然后使用Array 的标准map() 方法迭代结果

    let arr = [1,2,3,4,5,6,7,8,9];
    arr.slice(2, 6).map((element, index)=>console.log(element, index));

    【讨论】:

      【解决方案3】:

      您需要将Array#slice 作为第二个参数的索引,而不是部分的长度。只需添加索引即可。

      var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          index = 2,
          offset = 5,
          result = array.slice(index, index + offset);
      
      console.log(result);

      【讨论】:

        【解决方案4】:

        console.log([1,2,3,4,5,6,7,8,9,10].splice(2,5))

        【讨论】:

        • 这种方法会改变数组。这不是副作用,而是Array#splice的真正目的。
        【解决方案5】:

        slice() 应该满足你的要求:

        Array.prototype.slice(index, index + offset);
        

        【讨论】:

          猜你喜欢
          • 2014-12-19
          • 2015-10-09
          • 2014-07-08
          • 1970-01-01
          • 2022-08-08
          • 2020-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多