gpt4 book ai didi

javascript - 如何使用 For 循环在 JavaScript 中将元素添加到数组末尾

转载 作者:行者123 更新时间:2023-11-28 17:36:13 25 4
gpt4 key购买 nike

我有一个像这样的数组:

const r1 = 1.5;
const r4 = 2.7;
const r5 = 5.8;
const r6 = [r1, r4, r5];
document.write(r6);

我需要在数组的末尾添加以下元素r6:1 2 3 4 5 6 7 8 9 >10 .... 使用 For 循环最多可达 101,并使用 document.write(); 打印出来。

有人知道我该怎么做吗?

最佳答案

您正在寻找的方法是 .push(newElement) 。此方法将值附加到给定数组的末尾(在您的例子中是 r6)。

您可以在for内使用它像下面这样循环。

const r1 = 1.5;
const r4 = 2.7;
const r5 = 5.8;
const r6 = [r1, r4, r5];

// for iterates from 1 to 101
for (var i = 1; i <= 101; i++) {
r6.push(i); // adds the i element at the end of the r6 array
}

document.write(r6);

关于javascript - 如何使用 For 循环在 JavaScript 中将元素添加到数组末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com