我目前正在使用.each方法获取一个数组:
$.each(messages, function(key,message){ doStuff(); });
但是关键是数组的索引而不是关联键。
我该如何轻松获取它?
我目前正在使用.each方法获取一个数组:
$.each(messages, function(key,message){ doStuff(); });
但是关键是数组的索引而不是关联键。
我该如何轻松获取它?
JavaScript没有“关联数组”。它只有数组:
[1, 2, 3, 4, 5]
以及对象:
{a: 1, b: 2, c: 3, d: 4, e: 5}
数组没有“键”。它们有索引,索引从0开始计数。
数组使用[]
访问,对象可以使用[]
或.
访问。
示例:
var array = [1,2,3];
array[1] = 4;
console.log(array); // [1,4,3]
var obj = {};
obj.test = 16;
obj['123'] = 24;
console.log(obj); // {test: 16, 123: 24}
如果您尝试使用字符串作为键而不是整数来访问数组,可能会导致问题。您将设置数组的属性而不是值。
var array = [1,2,3];
array['test'] = 4; // This doesn't set a value in the array
console.log(array); // [1,2,3]
console.log(array.test); // 4
$.each
可以处理这两种情况。在$.each
的回调函数中,第一个参数key
既可以是对象的键,也可以是数组的索引。请注意保留HTML标签。$.each([1, 2, 3, 4, 5], function(key, value){
console.log(key); // Logs 0 1 2 3 4
});
$.each({a: 1, b: 2, c: 3, d: 4, e: 5}, function(key, value){
console.log(key); // Logs 'a' 'b' 'c' 'd' 'e'
});
var data = {
val1 : 'text1',
val2 : 'text2',
val3 : 'text3'
};
$.each(data, function(key, value) {
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
查看演示
JavaScript没有像PHP中的“关联数组”,而是使用对象。对象可以有与值对应的字符串键。数组是值的列表,索引为数字。因此,如果key
是一个数字,那么你正在使用的必须是一个数组而不是一个对象,因此你无法获取键,因为它不存在。
因此,你可能想要使用简单的for
循环来迭代数组,而不是基于回调的迭代器,如$.each
。
messages
在哪里?请发布它。 - thecodeparadoxvar h = new Array(); h['foo'] = 'bar'
。但是您没有添加新的数组元素,而是添加了一个名为“foo”的新属性。实际上,alert(h.length)
将为0
,并且您将具有alert(h.foo)
等于'bar'。 - ZER0messages
是什么以及您要查找的值吗? - gen_Eric