Array.from()的妙用

596 阅读1分钟

1.Array.from() 获取 undefined

let arr = Array.from(Array(3))
console.log(arr, 0)//[undefined,undefined,undefined]

2.获取 1985~1995之间的年份段

let arr1 = Array.from(Array(11))
arr1.forEach((item, index) => {
    arr1[index] = 1900 + index - 5
})
console.log(arr1, 1)//[1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905]
let arr2 = Array.from(Array(11))
arr2.forEach((item, index) => {
    arr2[index] = 1985 + index
})
console.log(arr2, 2)//[1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905]

3.获取 1995~1985之间的年份段

let arr3 = Array.from(Array(11))
arr3.forEach((item, index) => {
    arr3[index] = 1995 - index
})
console.log(arr3, 3)//[1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985] 

4.还可以获取偶数

let arr4 = Array.from(Array(11))
arr4.forEach((item, index) => {
    arr4[index] = index * 2
})
console.log(arr4, 4)//[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

5.获取含有12个月的数组

let monthArr = Array.from(Array(12))
monthArr = monthArr.map((_,i)=>{
    return i + 1 + '月'
})
console.log(monthArr);
// [
//     '1月',  '2月',  '3月',
//     '4月',  '5月',  '6月',
//     '7月',  '8月',  '9月',
//     '10月', '11月', '12月'
//   ]