简体   繁体   中英

Is there any way to find the position of a variable in an object in JavaScript

For example in

      {colour: 'red',x:0,y:20},
      {colour: 'orange',x:0,y:40},
      {colour: 'yellow',x:0,y:60},
      {colour: 'green',x:0,y:80},
      {colour: 'blue',x:0,y:90},
      {colour: 'purple',x:0,y:100},
      {colour: 'pink',x:0,y:120},
      {colour: 'brown',x:0,y:140},
      {colour: 'white',x:0,y:160},
      ]

Red is 0, orange is 1, etc.

You can do it like this

 var arr = [{colour: 'red',x:0,y:20}, {colour: 'orange',x:0,y:40}, {colour: 'yellow',x:0,y:60}, {colour: 'green',x:0,y:80}, {colour: 'blue',x:0,y:90}, {colour: 'purple',x:0,y:100}, {colour: 'pink',x:0,y:120}, {colour: 'brown',x:0,y:140}, {colour: 'white',x:0,y:160}, ]; var position = arr.findIndex(a=>a.colour == 'orange'); console.log(position);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM