Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
how can I split a string into an array with js

i have a problem why dispense doesn't get the amount of data that has been calculated by the loop.

why the demo2 doesn't count all the data totals and how to calculate the amount of data in the demo2?

const demo1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

const demo2 = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
const array_demo2 = [demo2];

let text1 = "";
let number1 = "";
for (let i = 0; i < demo1.length; i++) {
  number1 = (i + 1);
  text1 += demo1[i];
}

let text2 = "";
let number2 = "";
for (let i = 0; i < array_demo2.length; i++) {
  number2 = (i + 1);
  text2 += array_demo2[i];
}

document.getElementById("demo1").innerHTML = number1 +' = '+ text1;
document.getElementById("demo2").innerHTML = number2 +' = '+ text2;
<div style="display: flex"><p>Output 1 =></p>&nbsp;<p id="demo1"></p></div>
<div style="display: flex"><p>Output 2 =></p>&nbsp;<p id="demo2"></p></div>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

demo1 is an array, meaning multiple variables of the same type inside a container (the array is the container)

demo2 is a single variable, a string. you can

demo2.split(','); // to get an array like demo1, but it will be an array of strings.

array_demo2 is an array with a single element, the demo2 string. You can

array_demo2[0].split(','); // to get an array like demo2/demo1

Read more about arrays here The text is for C/++ but in Javascript arrays are very similiar.

about 4 years ago · Juan Pablo Isaza Report

0

const demo2 = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
const array_demo2 = [demo2];

this is not the correct way to convert it to number you're just passing a string in an array which will be on it's first index, so this array will have only 1 length.

its same like if you do lets say:

let fruit = "apple"
let fruits = [fruit];

fruits array will always have only one fruit on its first index. so the correct way is to use the .split method of array, so in your case it would be something

const demo2 = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
const array_demo2 = demo2.split(",");

now it will split each number seprated by "," and add it to new index on the array.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!