对象简写

js对象的属性计算名

1. 属性简写
const name = 'Alice';
const age = 30;

// 传统写法
const person = {
  name: name,
  age: age
};
//当属性名和变量名(是变量名,不是变量值)相同时:
// 简写
const person = { name, age };


2. 方法简写
 // 传统写法
const obj = {
  sayHello: function() {
    console.log('Hello');
  }
};

// 简写
const obj = {
  sayHello() {
    console.log('Hello');
  }
};

3. 计算属性名
4. const prop = 'name';

const obj = {
  [prop]: 'Alice',
  ['age']: 30,
  [`say${'Hello'}`]() {
    console.log('Hello');
  }
};

4. 对象展开运算符
 const obj1 = { a: 1, b: 2 };
 const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

5. 解构赋值
const person = { name: 'Alice', age: 30 };

// 传统写法
const name = person.name;
const age = person.age;

// 简写
const { name, age } = person;

// 重命名
const { name: personName } = person;


数组简写

1. 数组字面量简写
// 传统写法
const arr = new Array(1, 2, 3);

// 简写
const arr = [1, 2, 3];

2. 数组展开运算符

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]


3. 解构赋值

const arr = [1, 2, 3];

// 传统写法
const first = arr[0];
const second = arr[1];

// 简写
const [first, second] = arr;

// 跳过元素
const [first, , third] = arr;


4. 数组方法简写

// 传统写法
arr.map(function(item) {
  return item * 2;
});

// 简写
arr.map(item => item * 2);

5. 默认值
// 对象默认值
const { name = 'Anonymous', age = 0 } = {};

// 数组默认值
const [first = 0, second = 0] = [];

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐