如何在 Javascript 中将数值转换为数组。我想在循环中使用数组

问题描述 投票:0回答:2

这里我想使用数组方法'pop',但我不能 bcz num 有一个返回的整数值,所以我怎样才能将值变成一个数组。

let num = 0;
for(i=0; i<=10; i++){
    num = i
  let r = num.pop()
  console.log(num, r)
}

我期待着---

返回数字 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] & 控制台 [1, 2, 3, 4, 5, 6, 7, 8, 9] 10

javascript arrays for-loop methods numbers
2个回答
0
投票

您可以通过

num = []
初始化数组。

并且

num.pop()
将读取并删除元素。

这是修改后的代码

let num = []; 
for(i=1; i<=10; i++)
{     
num[i] = i   
let r = num[num.length - 1];   
console.log(num, r) 
}

0
投票

.pop() 是一个数组方法,它在这里不起作用,因为您的 num 变量不是数组。 您可以通过创建空数组的另一个变量并实际填充该变量来解决此问题。 像这样的东西 让 num_array = [];

© www.soinside.com 2019 - 2024. All rights reserved.