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
227 views
in Technique[技术] by (71.8m points)

javascript - 获取键/值javascript对象的键的最佳方法(best way to get the key of a key/value javascript object)

If I have a JS object like:(如果我有一个JS对象,例如:)

var foo = { 'bar' : 'baz' } If I know that foo has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it?(如果我知道foo具有基本的键/值结构,但不知道键的名称,那么最简单的方法是什么?) for ... in ?(for ... in ?) $.each() ?($.each()吗?) I hope there's something better....(我希望有更好的...)   ask by sprugman translate from so

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

1 Reply

0 votes
by (71.8m points)

You would iterate inside the object with a for loop:(您将使用for循环在对象内部进行迭代:)

for(var i in foo){ alert(i); // alerts key alert(foo[i]); //alerts key's value } Or(要么) Object.keys(foo) .forEach(function eachKey(key) { alert(key); // alerts key alert(foo[key]); // alerts value });

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

...