網站首頁 編程語言 正文
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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2021-12-03 Android識別NFC芯片制造商的方法_Android
- 2022-10-05 WPF實現好看的Loading動畫的示例代碼_C#教程
- 2023-03-20 C#如何刪除指定文件或文件夾_C#教程
- 2022-07-25 基于?Redis?實現接口限流的方式_Redis
- 2022-08-10 詳細聊一聊algorithm中的排序算法_C 語言
- 2023-01-12 Android?RecyclerChart其它圖表繪制示例詳解_Android
- 2022-06-02 docker基本命令及使用實例詳解_docker
- 2022-04-12 【debug】PytorchStreamReader failed reading zip arch
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支