简体   繁体   English

如何将多个元素添加到数组中

[英]How to add multiple elements into an Array

I'm trying to take an input from a text file (for example 3 7 9 53 2) and place those values into an array.我正在尝试从文本文件(例如 3 7 9 53 2)中获取输入并将这些值放入数组中。

3 7 9 53 2 3 7 9 53 2

I tried with prompt(), but I obviously can only add them one by one:我试过prompt(),但显然只能一一添加:

for (var i = 0; i < n; i++) {
    Array[i] = parseInt(prompt("Value for Array"));
}

However, I want to read line by line and add them to an array.但是,我想逐行读取并将它们添加到数组中。 A line will contain hundreds of numbers.一行将包含数百个数字。 is there a way to fill an array quickly by copying and pasting the data into the console?有没有办法通过将数据复制并粘贴到控制台来快速填充数组? Like in java就像在java中一样

String[] line = sc.nextLine().split(" ");

First use the split function to transform your string into array, then for each element of your array convert it into a number, Then you are done :)首先使用 split 函数将字符串转换为数组,然后将数组的每个元素转换为数字,然后就完成了:)

 var c = "12 2 23 3 4" var res = c.split(" ") for (var i=0; i < res.length; i++) { res[i] = parseInt(res[i]) } console.log(res)

Assume let result=[], so you want to add string in an array which can be directly assigned as "result=c.split(" ")" in case result is empty but if you want to assign multiple strings to the same array you can refer code.假设让 result=[],所以你想在一个数组中添加字符串,如果结果为空,则可以直接赋值为 "result=c.split(" ")" 但如果你想将多个字符串分配给同一个数组你可以参考代码。

var c = "12 2 23 3 4"
let d=" 1 2 3 4 5 6"
if(result.length === 0){
  result = c.split(" ")
}else{
 let tempArray = d.split(" ")
result.push(...tempArray)
}
console.log(result)```

You can do it with an inliner .split(" ") and .map(Number)你可以使用内联.split(" ").map(Number)

The first one will split the string by spaces, creating an array of each word/number, the second one will loop this array and convert every word to number, see below第一个将按空格拆分字符串,创建每个单词/数字的数组,第二个将循环此数组并将每个单词转换为数字,见下文

 let data = "3 7 9 53 2" let array = data.split(" ").map(Number) console.log(array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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