返回

ES 进阶技巧:JSON对象操作与自定义类型保护

前端

在 JavaScript 中,我们经常会遇到各种各样的代码技巧,这些技巧可以帮助我们更有效地编写代码。在本文中,我们将介绍一些 ES 中的代码小技巧,包括 JSON 对象操作、自定义类型保护、箭头函数、展开运算符、for...of、Promise、async/await、Proxy 等。

JSON 对象操作

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它被广泛用于 Web 开发。在 JavaScript 中,我们可以使用 JSON.parse() 和 JSON.stringify() 方法来解析和生成 JSON 字符串。

1. 使用 JSON.parse() 解析 JSON 字符串

const jsonStr = '{"name": "John Doe", "age": 30}';
const jsonObject = JSON.parse(jsonStr);

console.log(jsonObject.name); // "John Doe"
console.log(jsonObject.age); // 30

2. 使用 JSON.stringify() 生成 JSON 字符串

const jsonObject = {
  name: "John Doe",
  age: 30
};

const jsonStr = JSON.stringify(jsonObject);

console.log(jsonStr); // '{"name": "John Doe", "age": 30}'

自定义类型保护

在 JavaScript 中,我们可以使用 typeof 运算符来检查变量的类型。但是,typeof 运算符只能检查基本类型,对于自定义类型,它总是返回 "object"。

为了检查自定义类型的变量,我们可以使用 instanceof 运算符。instanceof 运算符可以检查一个变量是否属于某个类或接口。

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const person = new Person("John Doe", 30);

if (person instanceof Person) {
  console.log("person is a Person object");
} else {
  console.log("person is not a Person object");
}

箭头函数

箭头函数是一种简写函数语法。箭头函数没有自己的 this ,并且不能使用 arguments 对象。

// 普通函数
function add(a, b) {
  return a + b;
}

// 箭头函数
const add = (a, b) => a + b;

console.log(add(1, 2)); // 3

展开运算符

展开运算符(...)可以将数组或对象展开为单个元素。

// 数组展开
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];

console.log(newNumbers); // [1, 2, 3, 4, 5]

// 对象展开
const person = {
  name: "John Doe",
  age: 30
};

const newPerson = {
  ...person,
  job: "Software Engineer"
};

console.log(newPerson); // { name: 'John Doe', age: 30, job: 'Software Engineer' }

for...of

for...of 循环是一种遍历数组或对象的简便方法。

// 遍历数组
const numbers = [1, 2, 3];

for (const number of numbers) {
  console.log(number); // 1 2 3
}

// 遍历对象
const person = {
  name: "John Doe",
  age: 30
};

for (const key in person) {
  console.log(key); // "name" "age"
}

Promise

Promise 是一个对象,它代表着异步操作的最终完成或失败。

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello world!");
  }, 2000);
});

promise.then((result) => {
  console.log(result); // "Hello world!"
});

async/await

async/await 是 ES8 中引入的两个关键字,它们可以使异步代码看起来像同步代码。

async function greet() {
  const result = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Hello world!");
    }, 2000);
  });

  console.log(result); // "Hello world!"
}

greet();

Proxy

Proxy 是一个对象,它可以拦截对另一个对象的访问。

const person = {
  name: "John Doe",
  age: 30
};

const proxy = new Proxy(person, {
  get: function(target, property) {
    console.log(`Getting property ${property} from ${target}`);
    return target[property];
  },
  set: function(target, property, value) {
    console.log(`Setting property ${property} to ${value} on ${target}`);
    target[property] = value;
  }
});

proxy.name; // Getting property name from { name: 'John Doe', age: 30 }
proxy.age = 31; // Setting property age to 31 on { name: 'John Doe', age: 30 }