How to prevent automatic sort of Object numeric property?

后端 未结 10 1277
醉酒成梦
醉酒成梦 2020-12-03 20:57

Why I met this problem: I tried to solve an algorithm problem and I need to return the number which appeared most of the times in an array. Like [5,4,3,2,1,1] should return

10条回答
  •  我在风中等你
    2020-12-03 21:41

    You really can't rely on order of an object fields in JavaScript, but I can suggest to use Map (ES6/ES2015 standard) if you need to preserve order of your key, value pair object. See the snippet below:

    let myObject = new Map();
    myObject.set('z', 33);
    myObject.set('1', 100);
    myObject.set('b', 3);
    
    for (let [key, value] of myObject) {
      console.log(key, value);
    }
    // z 33
    // 1 100
    // b 3

提交回复
热议问题