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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

批量快捷創(chuàng)建新數(shù)組的幾種方式

作者:qq_42750608 更新時(shí)間: 2023-10-10 編程語(yǔ)言

1. for循環(huán), push(比較簡(jiǎn)單, 就不上代碼了)

2.創(chuàng)建空數(shù)組,填充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的第二個(gè)fn參數(shù)

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

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

eg:?Array.of(1, 2, 4, 7) => [1, 2, 4, 7]; 想變成新數(shù)組, 再鏈?zhǔn)秸{(diào)用map就行了

6. 手寫數(shù)據(jù)生成器:

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

1)?隨機(jī)數(shù)據(jù)生成器:

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

// createRandomValues(10) // 10個(gè)隨機(jī)數(shù)字組成的數(shù)組

2) 序列生成器

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

但是上面在(stop - start) / step有余數(shù)時(shí), stop沒有打印出來(lái), 因?yàn)椴环蟬tep的規(guī)律, 比如start為1,stop為99, step為3, 但是最后一個(gè)元素為97的時(shí)候就結(jié)束了:

// ?[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);

而有的時(shí)候, 或者說(shuō)大多數(shù)時(shí)候希望執(zhí)行到最后一個(gè)元素, 可以判斷arr[len -1]<stop的時(shí)候把stop的值push進(jìn)去

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

3) 生成對(duì)象數(shù)組

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

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

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