我想创建一个函数,它接受用户的输入并返回一个数组,其中包含从 1 到传递的数字的所有数字作为参数。示例:createArray(10) 应返回 [1,2,3,4,5,6,7,8,9,10]。我想出了这个解决方案:
function createArray(input) {
var value = 0;
var array = [];
for (i=0;i<input;i++) {
value++;
array.push(value)
console.log(array)
}
}
createArray(12);
正确且更好的做法是什么?
最佳答案
我更喜欢使用Array.from
:
const createArray = length => Array.from(
{ length },
// Mapper function: i is the current index in the length being iterated over:
(_, i) => i + 1
)
console.log(JSON.stringify(createArray(10)));
console.log(JSON.stringify(createArray(5)));
关于javascript - 创建数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51915681/