我正在连接的 API 返回一个对象。它的键/属性之一称为“长度”,这会触发一些奇怪的行为:
var obj = {"text1":{"index":0,"lengt":5}}; //modified key for testing
$.each(obj.text1,function(k,v){
console.log ('i: '+k+' v: '+v); });
i: index v: 0 //this is the result I'm looking for
i: lengt v: 5
var obj = {"text1":{"index":0,"length":5}}; //original object
i: 0 v: undefined // ????
i: 1 v: undefined
i: 2 v: undefined
i: 3 v: undefined
i: 4 v: undefined
我假设 length
是一个保留字,但这就是原始对象的来源。发现和规避此问题的最佳方法是什么?
非常感谢您的帮助。
最佳答案
这是 jquery 的“特性”;-)。根据消息来源,如果没有定义 length
属性,它将变量视为对象:
https://github.com/jquery/jquery/blob/master/src/core.js#L589
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
^---------
如果 isObj
是 false
- 那么请参阅 https://github.com/jquery/jquery/blob/master/src/core.js#L608
if ( isObj ) {
// not your case, ommitted
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
如您所见,它遍历 i
,从 0
到 length
关于javascript - js/jquery : issue with object key called "length",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13576387/