我有以下循环迭代数组,我尝试访问数组中当前位置的下一个位置。
for( var i in myArray){ var temp = myArray[i+1]; }问题是它没有添加1与var i,但它只是在i上添加数字1。 就像我是2,我这样做
i+1结果是
21而不是3。
为什么这样,我怎么能添加这两个变量?
i have the following loop which is iterating through an array and i try to access the next position of the current position in the array.
for( var i in myArray){ var temp = myArray[i+1]; }The problem is that it not add the 1 with the var i but it just appends the number 1 on the i. Like i is 2 and i do this
i+1the result is
21and not 3.
Why is this so and how can i add the two variables?
最满意答案
基本上,您正在迭代对象的键(数组是对象),键始终是字符串(或ES6中的符号类型) 。 要转换为数字,您只需在其前面添加一元plus号即可将带有数字的数字转换为数字。
var temp = myArray[+i + 1];您可以使用计数器更好地使用经典迭代,例如
var i, temp; for (i = 0; i < array.length; i++) { temp = array[i + 1]; // some more code }因为for ... in迭代对象的所有可枚举属性(如果存在)。 有关更多信息,请参阅为什么在数组迭代中使用“for ... in”是一个坏主意?
Basically you are iterating over the keys of an object (an array is an object) and the keys are always strings (or symbol type in ES6). For converting to a number, you could just add an unary plus in front of it for converting a stringed number to a number.
var temp = myArray[+i + 1];You might use better the classical iteration with a counter, like
var i, temp; for (i = 0; i < array.length; i++) { temp = array[i + 1]; // some more code }because for ... in iterates over all enumerable properties of the object, if exist. For more information read Why is using “for…in” with array iteration a bad idea?
更多推荐
发布评论