0

I am trying to convert an array of strings to an array of integers in javascript. I saw the following solution in a coupple of threads here and in a couple of other sources so I fuigure it must be correct, however when I get to the conversion the browser crashes. I have tried with Chromium and Firefox. Here is the source code, I am interested in what is causing this and what can be fixed:

 var str = "1,2,3,3,4,5,6";
 var arr1 = str.split(",");
 console.log(arr1);
  for(var k=0; k<=arr1.length; k++) { arr1[k] = +arr1[k]; }
0

2 Answers 2

1

In addition to the given answer, you may want to use this oneliner to create the array:

var arr1 = '1,2,3,4,5,6,7'.split(',').map(function(a){return +a;});

MDN page for Array.map

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is in this expression

k<=arr1.length

When k is 6, k++ increments k and it becomes 7. And then k <= arr1.length is true because arr1.length is 7. The next statement is

arr1[k] = +arr1[k];

which creates a new element in the array at index 7. So the array keeps on growing infinitely. What you should have done is

var arr1 = "1,2,3,3,4,5,6".split(",");
for (var k = 0; k < arr1.length; k++) {
    arr1[k] = +arr1[k];
}
console.log(arr1);
# [ 1, 2, 3, 3, 4, 5, 6 ]

Iterate only till the counter is lesser than length of the array. Otherwise store the length of the array in a temporary variable like this

for (var k = 0, len = arr1.length; k < len; k++) {
    arr1[k] = +arr1[k];
}

You can write the same as, simply

console.log("1,2,3,3,4,5,6".split(",").map(Number));
# [ 1, 2, 3, 3, 4, 5, 6 ]

2 Comments

Also it is always better to save array length in the variable before actual iterations for not checking the length in each pass.
You are correct. It's a very stupid mistake. I hadn't noticed the extra "=" unitl you pointed it out. It took me a good amount of time looking too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.