[JS] js dynamically adds, sets, and deletes attribute names and attribute values for objects

1. Access object properties

There are two ways to access object properties in js: dot acquisition method and square bracket acquisition method.

let user = {
    
         // 一个对象
  name: "John",  // 键 "name",值 "John"
  age: 30,        // 键 "age",值 30。列表中的最后一个属性应以逗号结尾:便于我们添加、删除和移动属性
};
  1. Access property values ​​using dot notationalert( user.name ); // John
  2. Use square brackets to access attribute valuesalert( user[name]); // John

Note: If we iterate over an object, do we get the properties in the same order they were added?
The short answer is: "in a particular order": integer attributes are sorted, other attributes appear in the order they were created.

2. Delete object properties

Delete object properties using deletekeywords

delete user.age;
delete user[age];

3. Dynamically set properties

The most commonly used object property acquisition method is the point acquisition method.
But when we need to dynamically add attributes and attribute values ​​​​to objects, the point-to-point method seems to be inconvenient, especially when we don't know the attribute name. At this time, 方括号the acquisition method comes in handy.

let order={
    
    
    id:1,
    name:'xxxx',
}
// 如果是直接给新属性赋值
order['logisticsNo']='xxxx';
 
// 如果添加的属性为[],则可以先创建属性值为空数组
order['logisticsNo']=[];
order['logisticsNo'].push(data); //注意数组才有push,不然会报错
 
// 也可以使用变量名
let key='logisticsNo';
order[key]=[];
order[key].push(data);

computed property

When creating an object, we can use square brackets in object literals. This is called a computed property .

let fruit = prompt("Which fruit to buy?", "apple");

let bag = {
    
    
  [fruit]: 5, // 属性名是从 fruit 变量中得到的
};

alert( bag.apple ); // 5 如果 fruit="apple"

The meaning of computed properties is simple: [fruit] means that the property name should be taken from the fruit variable.

So, if a user enters "apple", the bag will become {apple: 5}.

Essentially, this has the same effect as the following syntax:

let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
    
    };

// 从 fruit 变量中获取值
bag[fruit] = 5;

We can use more complex expressions inside square brackets:

let fruit = 'apple';
let bag = {
    
    
  [fruit + 'Computers']: 5 // bag.appleComputers = 5
};

Attribute existence judgment: "in" operator

Compared with other languages, JavaScript objects have a feature that needs attention: 能够被访问任何属性. Even if the attribute does not exist, no error will be reported!

Reading a property that doesn't exist will just get undefined. So we can easily tell if a property exists:

let user = {
    
    };

alert( user.noSuchProperty === undefined ); // true 意思是没有这个属性

in The left side of must be the property name. Usually a quoted string.

let user = {
    
     name: "John", age: 30 };

alert( "age" in user ); // true,user.age 存在
alert( "blabla" in user ); // false,user.blabla 不存在。

It is recommended to use it directly into determine whether the attribute of the object exists.

"for...in" loop

let user = {
    
    
  name: "John",
  age: 30,
  isAdmin: true
};

for (let key in user) {
    
    
  // keys
  alert( key );  // name, age, isAdmin
  // 属性键的值
  alert( user[key] ); // John, 30, true
}
  1. check for empty objects
function isEmpty(obj) {
    
    
  for (let key in obj) {
    
    
    // 如果进到循环里面,说明有属性。
    return false;
  }
  return true;
}
  1. sum of object properties
let salaries = {
    
    
  John: 100,
  Ann: 160,
  Pete: 130
};

let sum = 0;
for (let key in salaries) {
    
    
  sum += salaries[key];
}

alert(sum); // 390
  1. Multiply all numeric attribute values ​​by 2
// 在调用之前
let menu = {
    
    
  width: 200,
  height: 300,
  title: "My menu"
};

multiplyNumeric(menu);

// 调用函数之后
menu = {
    
    
  width: 400,
  height: 600,
  title: "My menu"
};

function multiplyNumeric(obj) {
    
    
  for (let key in obj) {
    
    
    if (typeof obj[key] == 'number') {
    
    
      obj[key] *= 2;
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_42960907/article/details/126071925