如何在JS中添加两个变量?(How to add two variables in JS?)

编程入门 行业动态 更新时间:2024-10-26 20:31:57
如何在JS中添加两个变量?(How to add two variables in JS?)

我有以下循环迭代数组,我尝试访问数组中当前位置的下一个位置。

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+1

the result is

21

and 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?

更多推荐

本文发布于:2023-07-24 00:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239039.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   两个   如何在   variables   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!