获取JavaScript对象的所有键 [英] Get all keys of a JavaScript object
本文介绍了获取JavaScript对象的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种快速方法可以将关联数组的键提取到数组中,或者使用JavaScript提取逗号分隔列表(jQuery没问题)。
I was wondering if there was a quick way to extract keys of associative array into an array, or comma-separated list using JavaScript (jQuery is ok).
options = {key1: "value1", key2: "value2"};
结果应该是数组:
["key1", "key2"]
或只是一个string:
or just a string:
"key1, key2"
推荐答案
您可以通过 for
循环轻松获取它们的数组,例如:
You can easily get an array of them via a for
loop, for example:
var keys = [];
for(var key in options) {
if(options.hasOwnProperty(key)) { //to be safe
keys.push(key);
}
}
然后使用键
你想要的,例如:
Then use keys
how you want, for example:
var keyString = keys.join(", ");
您可以在此处测试。 .hasOwnProperty()
检查是安全的,以防有人弄乱对象原型等。
You can test it out here. The .hasOwnProperty()
check is to be safe, in case anyone messed with the object prototype and such.
这篇关于获取JavaScript对象的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文