[英]Pushing string into an empty array with FOR Loop
The goal is to input a string "Item" into myArray with the function and input it the number of times that I indicate in the function arrayFiller parameter.目标是使用函数将字符串“Item”输入到 myArray 中,并输入我在函数 arrayFiller 参数中指定的次数。 Here's what I have so far.
这是我到目前为止所拥有的。 I am still new to FOR loops so I'm not sure what to put into the next two parameters in the FOR loop.
我对 FOR 循环仍然不熟悉,所以我不确定在 FOR 循环中的下两个参数中放入什么。 I'm guessing that I will need to use the .push object at some point but I've been trying this particular problem for so long.
我猜我在某个时候需要使用 .push 对象,但我一直在尝试这个特定的问题很长时间。
myArray = [];
function arrayFiller(times) {
for (i = 0; ;i++)
myArray.push[i];
}
arrayFiller(2);
arrayFiller(5) should add five different strings of "Item" in the empty array. arrayFiller(5) 应该在空数组中添加五个不同的“Item”字符串。
.push
is a method, so you need to use (
and )
to pass it the value to push into the array, not [
and ]
. .push
是一种方法,因此您需要使用(
and )
将值传递给它以推送到数组中,而不是[
和]
。 myArray = []; function arrayFiller(times, item) { for (i = 0; i < times; i++) myArray.push("Item"); } arrayFiller(5); console.log("# of items in array: " + myArray.length, myArray); myArray.length = 0; // Reset array arrayFiller(2); console.log("# of items in array: " + myArray.length, myArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.