Javascript :: 如何将关联数组的键获取到数组变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11561350/
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
Javascript :: How to get keys of associative array to array variable?
提问by ?mega
Let's have an associative array like this:
让我们有一个像这样的关联数组:
var aArray = {};
aArray.id = 'test';
aArray['x1'] = [1,2,3];
aArray['stackoverflow'] = 'What\'s up?';
aArray['x2'] = [4,5,6];
var keys = [];
for(var key in aArray) {
if (aArray.hasOwnProperty(key)) {
keys.push(key);
}
}
console.log(keys);
Is there any easy/short way how to get array of keys to array variable without loop?
是否有任何简单/简短的方法如何在没有循环的情况下获取数组变量的键数组?
If so, additionally, is possible to apply some regular expression to key list to get just keys that match such pattern (let's say/^x/
)without another loop?
如果是这样,另外,是否可以将一些正则表达式应用于键列表以仅获取与此类模式匹配的键(假设/^x/
)而无需另一个循环?
回答by T.J. Crowder
Is there any easy/short way how to get array of keys to array variable without loop..?
是否有任何简单/简短的方法如何在没有循环的情况下获取数组变量的键数组..?
Yes, ECMAScript 5 defines Object.keys
to do this. Most moderns browser engines will probably have it, older ones won't, but it's easily shimmed (for instance, this shimdoes).
是的,ECMAScript 5 定义Object.keys
了这样做。大多数现代浏览器引擎可能会有它,旧的不会,但它很容易被填充(例如,这个 shim有)。
If so, additionally, is possible to apply some regular expression to key list to get just keys that match such pattern (let's say
/^x/
) without (another) loop?
如果是这样,另外,是否可以将一些正则表达式应用于键列表以仅获取匹配此类模式的键(假设
/^x/
)而没有(另一个)循环?
No, no built-in functionality for that. Mind, it's a trivial function to write:
不,没有内置的功能。请注意,编写一个微不足道的函数:
function getKeys(obj, filter) {
var name,
result = [];
for (name in obj) {
if ((!filter || filter.test(name)) && obj.hasOwnProperty(name)) {
result[result.length] = name;
}
}
return result;
}
回答by scottheckel
In the year 2020, every browser supports this back to IE9. This is the way to go.
到 2020 年,每个浏览器都支持这个回到 IE9。这是要走的路。
JavaScript 1.8.5 has this functionality built in with Object.keys(). It returns an array of all of the keys. You could use a shim for non-supported browsers (MDN has help on that too).
JavaScript 1.8.5 在Object.keys() 中内置了这个功能。它返回一个包含所有键的数组。您可以为不受支持的浏览器使用 shim(MDN 也有帮助)。
As an example see this (jsFiddle)...
作为一个例子,看到这个(jsFiddle)...
var obj = { "cat" : "meow", "dog" : "woof"};
alert(Object.keys(obj)); // "cat,dog"