嗨的关键我目前获取的阵列。每个获取关联数组
$.each(messages, function(key,message){ doStuff(); });
但关键是数组的索引,而不是关联键。
我怎样才能很容易地得到它?
感谢
嗨的关键我目前获取的阵列。每个获取关联数组
$.each(messages, function(key,message){ doStuff(); });
但关键是数组的索引,而不是关联键。
我怎样才能很容易地得到它?
感谢
var data = {
val1 : 'text1',
val2 : 'text2',
val3 : 'text3'
};
$.each(data, function(key, value) {
alert("The key is '" + key + "' and the value is '" + value + "'");
});
见Demo
谢谢,我将使用一个数组来获得这项工作,你是对的 –
JavaScript没有 “关联数组”,如PHP,但对象。但是,对象可能具有对应于某个值的字符串键。数组是数值列表,因此,如果key
是一个数字,它必须是您正在使用的数组而不是对象,因此您无法获得密钥,因为没有数据。
因此,您可能想要使用简单的for
-loop代替基于回调的迭代器(如$.each
)遍历数组。
JavaScript没有“关联数组”。它有数组:
[1, 2, 3, 4, 5]
和对象:
{a: 1, b: 2, c: 3, d: 4, e: 5}
Array的没有 “钥匙”,他们有指标,其计数从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}
如果您尝试访问使用字符串作为密钥,而不是一个int,可能导致的一系列问题。您将设置数组的属性而不是值。
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
是对象的键或数组的索引。
$.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'
});
一个数组没有任何关联键。索引是关键。你想做什么? – Guffa
你在哪里Array即'messages'?发布 – thecodeparadox
您能否提供一个示例数组(2-3个元素)以及您期望的“关联密钥”? –