跳到主要内容

JS 小技巧

关于 JS 的一些总结, 持续更新中……

1、用??代替||,用于判断运算符左侧的值为 null 或 undefined 时,才返回右侧的值

??运算符是 ES2020 引入,也被称为 null 判断运算符( Nullish coalescing operator)
它的行为类似||,但是更严

||运算符是左边是空字符串或 false 或 0 等 falsy 值,都会返回后侧的值。而??必须运算符左侧的值为 null 或 undefined 时,才会返回右侧的值。因此 0||1 的结果为 1,0??1 的结果为 0

const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: "",
showSplashScreen: false,
},
};

const undefinedValue = response.settings.undefinedValue ?? "some other default"; // result: 'some other default'
const nullValue = response.settings.nullValue ?? "some other default"; // result: 'some other default'
const headerText = response.settings.headerText ?? "Hello, world!"; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

2、使用?.简化&&和三元运算符

?.也是 ES2020 引入,有人称为链判断运算符(optional chaining operator)
?.直接在链式调用的时候判断,判断左侧的对象是否为 null 或 undefined,如果是的,就不再往下运算,返回 undefined,如果不是,则返回右侧的值

let street = user.address && user.address.street;

let fooInput = myForm.querySelector("input[name=foo]");
let fooValue = fooInput ? fooInput.value : undefined;

// 简化
let street = user.address?.street;
let fooValue = myForm.querySelector("input[name=foo]")?.value;

注:常见写法
obj?.prop 对象属性
obj?.[expr] 对象属性
func?.(...args) 函数或对象方法的调用

3、使用 String.prototype.replaceAll()简化 replace 一次性替换所有子字符串

String.prototype.replaceAll()用法与 String.prototype.replace()类似
但是 replace 仅替换第一次出现的子字符串,而 replaceAll 会替换所有

例如需要替换所有 a 为 A:

// 以前
console.log("aaa".replace(/a/g, "A")); //AAA
// 简化后
console.log("aaa".replaceAll("a", "A")); //AAA

4、使用 Array.prototype.at()简化 arr.length

Array.prototype.at()接收一个正整数或者负整数作为参数,表示获取指定位置的成员 参数正数就表示顺数第几个,负数表示倒数第几个,这可以很方便的某个数组末尾的元素

let arr = [1, 2, 3, 4, 5];
// 以前获取最后一位
console.log(arr[arr.length - 1]); //5
// 简化后
console.log(arr.at(-1)); // 5

5、使用哈希前缀#将类字段设为私有

在类中通过哈希前缀#标记的字段都将被私有,子类实例将无法继承

class ClassWithPrivateField {
#privateField;
#privateMethod() {
return "hello world";
}
constructor() {
this.#privateField = 42;
}
}

const instance = new ClassWithPrivateField();
console.log(instance.privateField); //undefined
console.log(instance.privateMethod); //undefined

6、冻结对象

const oc = { key: 8, color: '#000' }
Object.freeze(oc);

oc.key = 10; // Error, 不会改变
connsole.log(oc); // { key: 8, color: '#000' }

7、将 Object 属性转成属性数组

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
// 输出
// (3) [Array(2), Array(2), Array(2)]
// 0: (2) ["a", 1]
// 1: (2) ["b", 2]
// 2: (2) ["c", 3]
// length: 3

Object.keys(obj);
// (3) ["a", "b", "c"]

Object.values(obj);
// (3) [1, 2, 3]