JavaScrpt中的...(三个点)运算以及?.和??运算

41 阅读2分钟

...运算

...运算符其实是取值运算,而且对于对象而言,这是一种浅拷贝,即指针指向的是同一个地址,当然,对于数组,数值而言,这种拷贝是深拷贝。

  • 示例1(数组和数值,深拷贝)

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

console.log(arr2); // 输出: [1, 2, 3]
console.log(arr1 === arr2); // 输出: false
  • 示例2(对象,浅拷贝)
const obj1 = { name: "John" };
const obj2 = { name: "Jane" };

const arr1 = [obj1, obj2];
const arr2 = [...arr1];

console.log(arr2); // 输出: [{ name: "John" }, { name: "Jane" }]
console.log(arr1[0] === arr2[0]); // 输出: true,引用相同的对象

以上两个示例分别展现了数组值类型的...运算以及对象的...运算,只要涉及对象,那么...运算都是一种浅拷贝

既然上面说到浅拷贝,如果我想要深拷贝呢,那么可以使用JSON.parse(JSON.stringify(object))

  • 示例3(JSON.parse(JSON.stringify(object)))
const obj1 = { name: "John" };
const obj2 = JSON.parse(JSON.stringify(obj1));

console.log(obj2); // 输出: { name: "John" }
console.log(obj1 === obj2); // 输出: false,已进行深拷贝

?.运算

?.运算是js中的一类特殊运算,又称为可选链运算,用来解决TypeError问题当发生TypeError问题发生时,返回undefined。比如访问的属性或者方法为null或者undefined时,直接返回undefined。

  • 示例1(属性)
const person = {
  name: "John",
  address: {
    city: "New York",
  },
};

console.log(person.address?.city); // 输出: "New York"
console.log(person.address?.country); // 输出: undefined
  • 示例2(方法)
const calculator = {
  add: function (a, b) {
    return a + b;
  },
};

console.log(calculator.add?.(2, 3)); // 输出: 5
console.log(calculator.multiply?.(2, 3)); // 输出: undefined

??运算

??运算是一种空值合并运算,一般用于取默认值,如果左边为null或者undefined,那么默认取右边的值。

  • 示例1
const value1 = null;
const value2 = 10;
const result = value1 ?? value2;
console.log(result); // 输出: 10
  • 示例2
const value1 = undefined;
const value2 = "Hello";
const result = value1 ?? value2;
console.log(result); // 输出: "Hello"

TypeError

上面我们说到一个TypeError错误,这是JavaScript中一种常见的错误,当在使用时,错误的引用或者引用不存在的对象或者方法时,便会抛出此类型的操作。

在web开发中,如果抛出这种错误,程序是会报错的,并且不会一般不能继续run下去。

所以在编写程序代码时,尽可能的避免这种调用,使用?.。

下面我们进行TypeError的示例展现

  • 调用一个非函数类型的值作为函数
const x = 42;
x(); // TypeError: x is not a function
  • 访问null或undefined值的属性或方法
const obj = null;
obj.property; // TypeError: Cannot read property 'property' of null

const arr = [1, 2, 3];
arr.method(); // TypeError: arr.method is not a function
  • 对不可变对象(如字符串、数字和布尔值)尝试修改其属性或方法
const str = "Hello";
str.push("!"); // TypeError: str.push is not a function

const num = 42;
num.toFixed(2); // TypeError: num.toFixed is not a function
  • 使用不支持的操作符或方法
const obj = {};
obj + 42; // TypeError: Cannot convert object to primitive value

const arr = [1, 2, 3];
arr.includes(4, "invalid"); // TypeError: Invalid value used in weak set

以上四个就是我们基本上遇到TypeError的情况。