简体   繁体   English

使用 FOR 循环将字符串推入空数组

[英]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 )将值传递给它以推送到数组中,而不是[]
  • You didn't configure your loop to have a looping condition.您没有将循环配置为具有循环条件。
  • You never wrote any code to inspect the array after the operation to know if it worked.您从未编写任何代码来在操作后检查数组以了解它是否有效。
  • Your code simply inserts the looping counter value into the array.您的代码只是将循环计数器值插入到数组中。 If you want something else (like "item"), you'd have to add that.如果你想要别的东西(比如“项目”),你必须添加它。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM