日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

批量快捷創建新數組的幾種方式

作者:qq_42750608 更新時間: 2023-10-10 編程語言

1. for循環, push(比較簡單, 就不上代碼了)

2.創建空數組,填充null,然后map:?

function createData() {
return new Array(1000)
.fill(null)
.map((v,i)=>({name: `name${i+1}`}))
}
console.log(createData())

3.Array.from+map

function createData() {
return Array.from({length: 1000})
.map((v,i)=>({name: `name${i+1}`}))
}
console.log(createData())

4.Array.from的第二個fn參數

function createData() {
return Array.from({length: 1000}, (v,i)=>({name: `name${i+1}`}))
}
console.log(createData())

5.?Array.of(...數組或類數組)

eg:?Array.of(1, 2, 4, 7) => [1, 2, 4, 7]; 想變成新數組, 再鏈式調用map就行了

6. 手寫數據生成器:

function createValues(creator, length = 1) {
    return Array.from({ length }, creator)
}

1)?隨機數據生成器:

const createRandomValues = (len) => createValues(Math.random, len)

// createRandomValues(10) // 10個隨機數字組成的數組

2) 序列生成器

const createRange = (start, stop, step) => {
    const arr = createValues((_, i) => start + (i * step), Math.floor((stop - start) / step) + 1)
    return arr
}

但是上面在(stop - start) / step有余數時, stop沒有打印出來, 因為不符合step的規律, 比如start為1,stop為99, step為3, 但是最后一個元素為97的時候就結束了:

// ?[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97]

createRange(1, 99, 3);

而有的時候, 或者說大多數時候希望執行到最后一個元素, 可以判斷arr[len -1]<stop的時候把stop的值push進去

const createRange = (start, stop, step) => {
    const arr = createValues((_, i) => start + (i * step), Math.floor((stop - start) / step) + 1)
    const len = arr.length
    // 如果最后一項小于stop的值, push一下stop的值
    if(arr[len -1]<stop) {
        arr.push(stop)
    }
    return arr
}

3) 生成對象數組

// 數據生成器:
function createUser(v, index) {
    return {
        name: `user-${index}`,
        //  0-100隨機數字, >> 0 取整
        age: Math.random() * 100 >> 0
    }
}
// 生成10條對象數據的數組
const users = createValues(createUser, 10)

原文鏈接:https://blog.csdn.net/qq_42750608/article/details/133363498

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新