【问题标题】:why I got error when "push" the element to array list in javascript?为什么在javascript中将元素“推送”到数组列表时出现错误?
【发布时间】:2021-10-17 10:47:48
【问题描述】:

我写了代码,但不知道错在哪里?

我想通过for/loop和push来填充numberList数组从1到6。

let numberList = [];


for (let i = 0; i <= 6; i++) {
  numberList[i].push();
}
console.log(numberList);

【问题讨论】:

标签: javascript arrays push


【解决方案1】:

您当前的语法错误。实际的Array.prototyp.push() 语法如下所示,

push(element0)
push(element0, element1)
push(element0, element1, ... , elementN)

代码::如果想用for/loop填充numberList数组从1到6并push,那么i从1开始,而不是0

let numberList = [];
for (let i = 1; i <= 6; i++) {
  numberList.push(i);
}
console.log(numberList);

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 1970-01-01
    • 2021-12-03
    • 2021-08-09
    • 1970-01-01
    • 2022-06-15
    • 2015-06-11
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多