如何使用 jQuery 获取数组键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1254227/
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-26 11:00:45  来源:igfitidea点击:

how to fetch array keys with jQuery?

jqueryarrayskey

提问by Stefan Konno

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.

下午好。我有一个包含一些键和值的数组。然后我需要获取数组键而不是其中的数据。我想用 jQuery 做到这一点。例如,我知道 PHP 有一个名为 array_keys() 的函数;它将数组作为参数,并为您返回一个数组,其中包含每个索引中的每个键。

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

This will output;

这将输出;

alfa
beta

But is there any predefined function for this, as in PHP or any other more effective way of getting this?

但是是否有任何预定义的函数,如在 PHP 中或任何其他更有效的方法?

回答by dfa

you can use the eachfunction:

您可以使用该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

它有几个不错的快捷方式/技巧:在此处查看血腥细节

回答by dugokontov

Using jQuery, easiest way to get array of keys from object is following:

使用 jQuery,从对象获取键数组的最简单方法如下:

$.map(obj, function(element,index) {return index})

In your case, it will return this array: ["alfa", "beta"]

在您的情况下,它将返回此数组: ["alfa", "beta"]

回答by Andy

console.log( Object.keys( {'a':1,'b':2} ) );

回答by Joshua Pinter

Don't Reinvent the Wheel, Use Underscore

不要重新发明轮子,使用下划线

I know the OP specifically mentioned jQuerybut I wanted to put an answer here to introduce people to the helpful Underscorelibrary if they are not aware of it already.

我知道 OP 特别提到了jQuery,但我想在这里给出一个答案,向人们介绍有用的Underscore库,如果他们还没有意识到的话。

By leveraging the keysmethod in the Underscore library, you can simply do the following:

通过利用Underscore 库中keys方法,您可以简单地执行以下操作:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

此外,还有许多其他有用的功能值得细读。

回答by Russ Cam

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

为此使用对象(键/值对,最接近关联数组的 JavaScript)而不是数组对象。除此之外,我相信这是最优雅的方式

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

注意:JavaScript 不保证属性的任何特定顺序。因此,您不能期望首先定义的属性首先出现,它可能最后出现。

EDIT:

编辑:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

针对您的评论,我相信这篇文章最好地总结了为什么不应该以这种方式使用 JavaScript 中的数组的案例 -

回答by MistereeDevlord

I use something like this function I created...

我使用类似我创建的这个函数的东西......

Object.getKeys = function(obj, add) {
    if(obj === undefined || obj === null) {
        return undefined;
    }
    var keys = [];
    if(add !== undefined) {
        keys = jQuery.merge(keys, add);
    }
    for(key in obj) {
        if(obj.hasOwnProperty(key)) {
                keys.push(key);
        }
    }
    return keys;
};

I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

我认为您可以在第一次测试中将 obj 设置为 self 或更好的东西。似乎有时我也在检查它是否也是空的,所以我就是这样做的。此外,我不认为 {} 是 Object.* 或者至少在以这种方式在 Object 上找到函数 getKeys 存在问题。也许您想将原型放在首位,但这似乎会导致与 GreenSock 等发生冲突。