最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there any way to loop randomly through the keys of an object? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

Yes. 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]);})();
发布评论

评论列表(0)

  1. 暂无评论