如何使用 jQuery 获取数组键? [英] how to fetch array keys with jQuery?
问题描述
下午好.我有一个包含一些键和值的数组.然后我需要获取数组键而不是其中的数据.我想用 jQuery 做到这一点.例如,我知道 PHP 有一个名为 array_keys() 的函数;它将数组作为参数,并为您返回一个数组,其中包含每个索引中的每个键.
Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for example that PHP has a function called array_keys(); which takes the array as a parameter and gives you an array back with each key in each index.
这就是我想出来的,它有效……唯一的问题是它看起来效率很低;
This is what I came up with, and it works... the only problem is that it seems so unefficent;
var foo = [];
foo['alfa'] = "first item";
foo['beta'] = "second item";
for (var key in foo) {
console.log(key);
}
这将输出;
alfa
beta
但是是否有任何预定义的函数,如在 PHP 中或任何其他更有效的方法?
But is there any predefined function for this, as in PHP or any other more effective way of getting this?
推荐答案
你可以使用each
函数:
var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
alert(key)
});
它有几个不错的快捷方式/技巧:在这里查看详细信息
it has several nice shortcuts/tricks: check the gory details here
这篇关于如何使用 jQuery 获取数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!