Skip to content

优雅地创建 1 到 N 的数组

Published: at 10:46 AMSuggest Changes

创建一个这样的数组:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[ ...Array(N).keys() ].map( i => i+1);

Array(N).fill().map((_, i) => i+1);

Array.from(Array(N), (_, i) => i+1)

Array.from({ length: N }, (_, i) => i+1)

Array.from({length: 5}, (v, k) => k+1); 
// [1,2,3,4,5]

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var N = 10; 
Array.apply(null, {length: N}).map(Number.call, Number)
// result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.apply(null, {length: N}).map(Function.call, Math.random)
// result: [0.7082694901619107, 0.9572225909214467, 0.8586748542729765, 0.8653848143294454, 0.008339877473190427, 0.9911756622605026, 0.8133423360995948, 0.8377588465809822, 0.5577575915958732, 0.16363654541783035]

后记

代码都是从网上抄下来的,Mark 一下 https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n


Previous Post
JS 正则匹配 HTML 标签并去除
Next Post
提取 CODEIF 核心代码片段