Can I loop through a javascript object in reverse order?

后端 未结 4 773
感情败类
感情败类 2021-02-03 17:44

So I have a JavaScript object like this:

foo = {
  \"one\": \"some\",
  \"two\": \"thing\",
  \"three\": \"else\"
};

I can loop this like:

4条回答
  •  滥情空心
    2021-02-03 18:33

    There is no way to loop through an object backwards, but if you recreate the object in reverse order then you are golden! Be cautions however, there is nothing that says the order of the object will stay the same as it changes and so this may lead to some interesting outcome, but for the most part it works...

    function ReverseObject(Obj){
        var TempArr = [];
        var NewObj = [];
        for (var Key in Obj){
            TempArr.push(Key);
        }
        for (var i = TempArr.length-1; i >= 0; i--){
            NewObj[TempArr[i]] = [];
        }
        return NewObj;
    }
    

    The just do the swap on your object like this-

    MyObject = ReverseObject(MyObject);
    

    The loop would then look like this-

    for (var KeysAreNowBackwards in MyObject){
        alert(MyObject[KeysAreNowBackwards]);
    } 
    

提交回复
热议问题