[英]Array conversion from string to int crashes the browser
I am trying to convert an array of strings to an array of integers in javascript. 我正在尝试将字符串数组转换为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.
我已经尝试使用Chromium和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]; }
The problem is in this expression 问题是在这个表达
k<=arr1.length
When k
is 6
, k++
increments k
and it becomes 7
. 当
k
为6
, k++
k
递增,并变为7
。 And then k <= arr1.length
is true because arr1.length
is 7. The next statement is 然后
k <= arr1.length
为true,因为arr1.length
为7。
arr1[k] = +arr1[k];
which creates a new element in the array at index 7. So the array keeps on growing infinitely. 它在索引为7的数组中创建一个新元素。因此,数组将继续无限增长。 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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.