How to access the first property of a Javascript object?

前端 未结 19 2742
爱一瞬间的悲伤
爱一瞬间的悲伤 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:24

    var obj = { first: 'someVal' };
    obj[Object.keys(obj)[0]]; //returns 'someVal'
    

    Using this you can access also other properties by indexes. Be aware tho! Object.keys return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.

提交回复
热议问题