简体   繁体   中英

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

I tried with prompt(), but I obviously can only add them one by one:

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

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 :)

 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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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