如何得到一个年份前5位和后5位组成的数组?

86 阅读1分钟

1.实现步骤

// 假设给定时间为2020年
const arr = Array(11) // [empty × 11]
const newArr = Array.from(arr,(value,index) =>{
    // value 为arr数组的元素,index为数组的索引
    return  2020 + index - 5
})
// newArr =[2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025]

2.Array()方法

Array()  构造器用于创建 Array 对象

Array()若传入单个数字则可以得到一个长度为传入数字,所有值为 undefined 的新数组 如果向构造器传入多个参数则会创建一个包含所有传入参数的新数组

3.Array.from()方法

Array.from()  方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例

Array.from(arrayLike[, mapFn[, thisArg]])
  • arrayLike想要转换成数组的伪数组对象或可迭代对象。

  • mapFn 可选 如果指定了该参数,新数组中的每个元素会执行该回调函数。

  • thisArg 可选 可选参数,执行回调函数 mapFn 时 this 对象。

  • 返回值为一个新的数组实例

4.拓展

Array.fill()  方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引

arr.fill(value[, start[, end]])

  • value 用来填充数组元素的值。
  • start 起始索引,默认值为0可选
  • end 终止索引,默认值为 this.length
  • 返回值为修改后的数组。