Javascript 获取关联数组的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10936413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:38:50  来源:igfitidea点击:

Get key of associative array

javascriptjqueryarrays

提问by Asai Lopze

Hi i'm currently fetching an array with .each

嗨,我目前正在使用 .each 获取一个数组

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

But the key is the index of the array and not the associative key.

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

How can I get it easily?

我怎样才能轻松获得它?

Thanks

谢谢

回答by Rocket Hazmat

JavaScript doesn't have "associative arrays". It has arrays:

JavaScript 没有“关联数组”。它有数组:

[1, 2, 3, 4, 5]

and objects:

和对象:

{a: 1, b: 2, c: 3, d: 4, e: 5}

Array's don't have "keys", they have indices, which are counted starting at 0.

数组没有“键”,它们有索引,从 0 开始计数。

Arrays are accessed using [], and objects can be accessed using []or ..

使用 访问数组[],使用[]或访问对象.

Example:

例子:

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}

If you try to access an array using a string as a key instead of an int, that may cause problems. You would be setting a property of the array and not a value.

如果您尝试使用字符串而不是 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's $.eachworks with both of these. In the callback for $.each, the 1st param, key, is either the object's key, or the array's index.

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'
});

回答by Nishu Tayal

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

See the Demo

演示

回答by Sune Rasmussen

JavaScript doesn't have "associative arrays" as in PHP, but objects. Objects, though, may have string keys that corresponds to a value. Arrays are lists of values indexed numerically, so, if keyis a number, it must be an array you are working with and not an object, and therefore you cannot get the key, as there is none.

JavaScript 没有 PHP 中的“关联数组”,而是对象。但是,对象可能具有与值对应的字符串键。数组是按数字索引的值列表,因此,如果key是数字,则它必须是您正在使用的数组而不是对象,因此您无法获取键,因为没有键。

Thus, you'd probably want to iterate over an array with a simple for-loop instead of a callback-based iterator such as $.each.

因此,您可能希望使用简单的for-loop 而不是基于回调的迭代器(例如$.each.