How to add a new property to an object in an array of objects in JavaScript

var a =[{name: 'Tom',age:20},{name: 'Tom2',age:22}]

  Now add a gender attribute to the first object in the a array

a[0]['gender']='women'
a[0]['address']="China"
a[1].province="Jiangsu"

  Some more attributes have been added to distinguish between single and double quotation marks in strings.

Used. No square brackets and no single quotation marks

Use square brackets and single quotes without dots

 

The above is the effect;

What happens if you are not careful and do not specify the number of objects in the array and directly match the a array?

a.hahaha=123

  At this time, the length of the array is still 2, and the content becomes

If I don't randomly find a hahaha, but use a keyword, as shown below, the length of the array becomes 3

a.push({name:'Jack'})

  

 

What if you want to delete the Jack object?

delete a[2]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324708127&siteId=291194637