JavaScript-javascript 的自动转型异常
var map = [1,2,3,4]
var arr = [1,2,3]
for(var i in arr){
var k = map[i+1]; // 有的时候这里的i+1被当作字符串直接连接了,如果 i=1, i+1=11.
// 表现出非常诡异的问题
// 必需改为 map[parseInt(i)+1],才等得到预期的结果
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个其实没什么难理解的,仔细的看看JavaScript上对for/in循环的解释就清楚了,for/in是可以循环一个对象,并把对象的属性值作为字符串类型进行遍历,所以就有你问题里出现的问题了,以下javascritp手册(英文版)里对for/in的解释:
The for/in statement provides a way to loop through the properties of an object. The body of the for/in loop is executed once for each property of object. Before the body of the loop is executed, the name of one of the object's properties is assigned to variable, as a string. Within the body of the loop, you can use this variable to look up the value of the object's property with the [] operator.
The for/in loop does not specify the order in which the properties of an object are assigned to the variable. There is no way to tell what the order will be in advance, and the behavior may differ among implementations or versions of JavaScript. If the body of a for/in loop deletes a property that has not yet been enumerated, that property will not be enumerated. If the body of the loop defines new properties, whether or not those properties will be enumerated by the loop is implementation-dependent.
The for/in loop does not actually loop through all possible properties of all objects. In the same way that some object properties are flagged to be read-only or permanent (nondeletable), certain properties are flagged to be nonenumerable. These properties are not enumerated by the for/in loop. While all user-defined properties are enumerated, many built-in properties, including all built-in methods, are not enumerated.
var map = [1,2,3,4]
var arr = [1,2,3]
for(var i in arr){
var k = map[i+1]; // 有的时候这里的i+1被当作字符串直接连接了,如果 i=1, i+1=11.
// 表现出非常诡异的问题
// 必需改为 map[parseInt(i)+1],才等得到预期的结果
}
可能是js是弱类型语言的更新吧
(错误答案,请略过)自动转型是以第一个运算对象为基准的,也就是说“+”号前面是什么类型就会以什么类型进行运算。
var map = [1,2,3,4]
var arr = [1,2,3]
for(var i in arr){
alert(typeof i);
var k = map[i+1]; // 有的时候这里的i+1被当作字符串直接连接了,如果 i=1, i+1=11.
// 表现出非常诡异的问题
// 必需改为 map[parseInt(i)+1],才等得到预期的结果
}
输出是 string
所以这里的运算是string的“+”运算。
你可以写成“map[1+i]”,这样就是数字的“+”运算
补充:
在ECMA-262中有这样的描述
所以只要有string结果就是string,但是“-”、“*”、“/”等都是number的
建议改成这样方式:
var map = [1,2,3,4]
var arr = [1,2,3]
for(var i=0; i < arr.length; i++){
var k = map[i+1];
console.info(typeof(arr[i]),i,k)
}
//for(var i in arr)对象i属性类型为string.
var map = [1,2,3,4]
var arr = [1,2,3]
for(var i in arr){
var k = map[i+1];
console.info(typeof i)// string.
}