How to access the first property of a Javascript object?

前端 未结 19 2744
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 09:00

Is there an elegant way to access the first property of an object...

  1. where you don\'t know the name of your properties
  2. without using a loop like
19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 09:46

    Use an array instead of an object (square brackets).

    var example = [ {/* stuff1 */}, { /* stuff2 */}, { /* stuff3 */}];
    var fist = example[0];
    

    Note that you lose the 'foo' identifiers. But you could add a name property to the contained objects:

    var example = [ 
      {name: 'foo1', /* stuff1 */},
      {name: 'foo2', /* stuff2 */},
      {name: 'foo3', /* stuff3 */}
    ];
    var whatWasFirst = example[0].name;
    

提交回复
热议问题