获取关联数组的键

5

我目前正在使用.each方法获取一个数组:

$.each(messages, function(key,message){ doStuff(); });

但是关键是数组的索引而不是关联键。

我该如何轻松获取它?


5
数组没有关联键,索引就是键。你想要做什么? - Guffa
2
你的数组 messages 在哪里?请发布它。 - thecodeparadox
1
请提供一个包含2-3个元素的示例数组,并说明您期望的“关联键”。 - Alexei Levenkov
1
JavaScript没有关联数组。在JS中,您可以使用对象来模拟使用方括号表示法,但是您正在添加属性。我相信您犯了一个常见的错误,例如:var h = new Array(); h['foo'] = 'bar'。但是您没有添加新的数组元素,而是添加了一个名为“foo”的新属性。实际上,alert(h.length)将为0,并且您将具有alert(h.foo)等于'bar'。 - ZER0
"key是数组的索引,而不是关联键。" 什么意思? 数组没有“关联键”。您能展示一下messages是什么以及您要查找的值吗? - gen_Eric
3个回答

21

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

jQuery的$.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'
});

夸赞优雅的jQuery each方法! - David A. Gray

10
var data = {
    val1 : 'text1',
    val2 : 'text2',
    val3 : 'text3'
};
$.each(data, function(key, value) {
    alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
​

查看演示


0

JavaScript没有像PHP中的“关联数组”,而是使用对象。对象可以有与值对应的字符串键。数组是值的列表,索引为数字。因此,如果key是一个数字,那么你正在使用的必须是一个数组而不是一个对象,因此你无法获取键,因为它不存在。

因此,你可能想要使用简单的for循环来迭代数组,而不是基于回调的迭代器,如$.each


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接