Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...