admin管理员组文章数量:1391787
I have a for loop that looks something like
for (var key in myObjectArray) {
[code]
}
I would like to do the same thing except have the order of the output shuffled every time.
Is there any easy way to do it? I can make a separate array of keys, sort them, and then do a for loop with an index… but that seems like a lot of work and rather inefficient.
I have a for loop that looks something like
for (var key in myObjectArray) {
[code]
}
I would like to do the same thing except have the order of the output shuffled every time.
Is there any easy way to do it? I can make a separate array of keys, sort them, and then do a for loop with an index… but that seems like a lot of work and rather inefficient.
Share Improve this question asked Dec 14, 2013 at 22:54 Dan GoodspeedDan Goodspeed 3,5905 gold badges29 silver badges35 bronze badges 4- stackoverflow./questions/2450954/… – Robert Harvey Commented Dec 14, 2013 at 22:55
- It's already somewhat randomly, as order is not guaranteed in an object. – adeneo Commented Dec 14, 2013 at 22:55
- 3 @adeneo Not guaranteed, but deterministic nevertheless. – Robert Harvey Commented Dec 14, 2013 at 22:57
- Pretty sure chrome sorts objects first by integers then lexicographically, but don't quote me – user1382306 Commented Jul 26, 2014 at 5:05
1 Answer
Reset to default 10Yes. First, you need an array of keys:
var keys;
if( Object.keys) keys = Object.keys(myObjectArray);
else keys = (function(obj) {var k, ret = []; for( k in obj) if( obj.hasOwnProperty(k)) ret.push(k); return ret;})(myObjectArray);
// isn't browser patibility fun?
Next, shuffle your array.
keys.sort(function() {return Math.random()-0.5;});
// there are better shuffling algorithms out there. This works, but it's imperfect.
Finally, iterate through your array:
function doSomething(key) {
console.log(key+": "+myObjectArray[key]);
}
if( keys.forEach) keys.forEach(doSomething);
else (function() {for( var i=0, l=keys.length; i<l; i++) doSomething(keys[i]);})();
本文标签: javascriptIs there any way to loop randomly through the keys of an objectStack Overflow
版权声明:本文标题:javascript - Is there any way to loop randomly through the keys of an object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744772550a2624428.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论