Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

javascript - 获取对象键的数组(Get array of object's keys)

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.(我想以jQuery或纯JavaScript的形式获取JavaScript对象的键作为数组。)

Is there a less verbose way than this?(有没有比这更详细的方法?) var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' }; var keys = []; for (var key in foo) { keys.push(key); }   ask by Richard translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Object.keys :(使用Object.keys :)

var foo = { 'alpha': 'puffin', 'beta': 'beagle' }; var keys = Object.keys(foo); console.log(keys) // ['alpha', 'beta'] // (or maybe some other order, keys are unordered). This is an ES5 feature.(这是ES5的功能。) This means it works in all modern browsers but will not work in legacy browsers .(这意味着它可以在所有现代浏览器中使用,但不能在旧版浏览器中使用 。) The ES5-shim has a implementation of Object.keys you can steal(ES5-shim具有可以窃取的Object.keys实现)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...