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]; }
有帮助吗?

解决方案 2

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 ]

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top