JavaScript 中只有一个数字的数组映射

სალ*_*იძე 1 javascript

我想用一个数字创建数组。是否可以?

在 array = 60 中,我的意思是 array[1, 2, 3 ...60],但我想要这个数组只有一个数字。

我想要这样的东西。

JavaScript:

let array = 60;
const map1 = array.map(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)

console.log 必须出现 60 次。

Rey*_*yno 9

您可以使用 来new Array(60);创建长度为 60 的数组。然后附加fill("")来用空字符串填充数组。之后,您可以将map()每个项目的索引为其值。

(请注意,索引是从零开始的,因此您需要加一)。

let arr = new Array(60).fill("").map((_, i) => i + 1);

arr.forEach(n => console.log(n));
Run Code Online (Sandbox Code Playgroud)

详细的:

// Create array of length 60
let arr = new Array(60);

// Fill the whole array with a value, i chose empty strings
let filledArr = arr.fill("");

// Replace every value with it's index plus one. Index starts at 0 that's why we add one
let numArr = filledArr.map((_, i) => i + 1);
Run Code Online (Sandbox Code Playgroud)

编辑:通过将其变成一个函数,您可以使用动态长度来调用它

// Create array of length 60
let arr = new Array(60);

// Fill the whole array with a value, i chose empty strings
let filledArr = arr.fill("");

// Replace every value with it's index plus one. Index starts at 0 that's why we add one
let numArr = filledArr.map((_, i) => i + 1);
Run Code Online (Sandbox Code Playgroud)

  • @სალისულაბერიძე这是因为在stackoverflow上我们只能在控制台中显示50行。如果您将其复制到您自己的代码中,它应该显示全部 60 个。 (2认同)