JS总结之超级有用的JavaScript 技巧

1. 多条件 if 语句

将多个值放入一个数组中,然后调用该数组的 include 方法。

☘️ 普通写法
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
  //logic
}
☘️ 简写方法
if (["abc", "def", "ghi", "jkl"].includes(x)) {
  //logic
}

2. 简化 if true...else 条件表达式

☘️ 普通写法
let test: boolean;
if (x > 100) {
  test = true;
} else {
  test = false;
}
☘️ 简写方法
let test = x > 10 ? true : false;
//or let test = x > 10;
console.log(test);

3. 假值(undefined, null, 0, false, NaN, empty string)检查

当我们创建一个新变量时,有时我们想检查引用的变量是否是一个假值,例如 null 或 undefined 或空字符串。JavaScript 确实为这种检查提供了一个很好的快捷方式——逻辑 OR 运算符 (||)

|| 仅当左侧为空或 NaN 或 null 或 undefined 或 false 时,如果左侧操作数为假,则将返回右侧操作数,逻辑或运算符 ( || ) 将返回右侧的值。

☘️ 普通写法
if (test1 !== null || test1 !== undefined || test1 !== "") {
  let test2 = test1;
}
☘️ 简写方法
let test2 = test1 || "";

4. null/undefined 检查和默认赋值

☘️ null checking and default assignment
let test1 = null;
let test2 = test1 ?? "";
console.log("null check", test2); // output empty string ""
☘️ undefined checking and default assignment
const test = undefined ?? "default";
console.log(test);// expected output: "default"

5. 使用可选的链接运算符 -?。

? 也称为链判断运算,它允许开发人员读取深度嵌套在对象链中的属性值,而无需验证每个引用,当引用为空时,表达式停止计算并返回 undefined。

const travelPlans = {
  destination: "DC",
  monday: {
    location: "National Mall",
    budget: 200, 
  }, };
☘️ 普通写法
const res = travelPlans && travelPlans.tuesday && travelPlans.tuesday.location && travelPlans.tuesday.location.href;
console.log(res); // Result: undefined
☘️ 简写方法
const res1 = travelPlans?.tuesday?.location?.href;
console.log(res1); // Result: undefined

6. 开关简化

我们可以将条件存储在键值对象中,并根据条件调用它们。

☘️ 普通写法
switch (data) {
    case 1:
        test1();
        break;
    case 2:
        test2();
        break;
    case 3:
        test();
        break; // And so on...
}
☘️ 简写方法
var data = {
 1: test1,
 2: test2,
 3: test,
};
// If type exists in data, execute the corresponding function
data[type] && data[type]();

7. 默认参数值

☘️ 普通写法
function add(test1, test2) {
    if (test1 === undefined) test1 = 1;
    if (test2 === undefined) test2 = 2;
    return test1 + test2;
}
☘️ 简写方法
add = (test1 = 1, test2 = 2) => test1 + test2;add(); //output: 3

8. 条件查找简化

如果我们想根据不同的类型调用不同的方法,我们可以使用多个 else if 语句或开关,但是还有比这更好的简化技巧吗?其实和之前的switch简化是一样的。

☘️ 普通写法
if (type === "test1") {
    test1();
} else if (type === "test2") {
    test2();
} else if (type === "test3") {
    test3();
} else if (type === "test4") {
    test4();
} else {
    throw new Error("Invalid value " + type);
}
☘️ 简写方法
var types = { test1, test2, test3, test4, }; 
types[type] && types[type]();

9. 对象属性赋值

let test1 = "a";let test2 = "b";

☘️ 普通写法
let obj = { test1: test1, test2: test2 };
☘️ 简写方法
let obj = { test1, test2 };

10. 解构赋值

☘️ 普通写法
const test1 = this.data.test1;
const test2 = this.data.test2;
const test3 = this.data.test3;
☘️ 简写方法
const { test1, test2, test3 } = this.data;

11. 模板字符串

如果你厌倦了使用 + 将多个变量连接成一个字符串,这个简化技巧会让你头疼。

☘️ 普通写法
const welcome = "Hi " + test1 + " " + test2 + ".";
☘️ 简写方法
const welcome = `Hi ${test1} ${test2}`;

12. 跨越字符串

☘️ 普通写法
const data =
"hello maxwell this is a test\n\t" + "test test,test test test test\n\t";
☘️ 好的
const data = `hello maxwell this is a test
test test,test test test test`;

13. indexOf的按位化简

在数组中查找某个值时,我们可以使用 indexOf() 方法。但是还有更好的方法,我们来看这个例子。

☘️ 普通写法
if (arr.indexOf(item) > -1) {
    // item found
}
if (arr.indexOf(item) === -1) {
    // item not found
}
☘️ 简写方法
if (~arr.indexOf(item)) {
    // item found
}
if (!~arr.indexOf(item)) {
    // item not found
}

14. 将字符串转换为数字

有诸如 parseInt 和 parseFloat 等内置方法可用于将字符串转换为数字。我们也可以简单地通过在字符串前面提供一元运算符 (+) 来做到这一点。

☘️ 普通写法
let total = parseInt("583");
let average = parseFloat("32.5");
☘️ 简写方法
let total = +"583";
let average = +"32.5";

15. 合并数组

☘️ 普通写法

我们通常使用Array中的concat()方法合并两个数组。用concat()方法来合并两个或多个数组,不会更改现有的数组,而是返回一个新的数组。请看一个简单的例子:

let apples = ['??', '??'];
let fruits = ['??', '??', '??'].concat(apples);
console.log( fruits );  //结果:["??", "??", "??", "??", "??"]
☘️ 简写方法

我们可以通过使用ES6扩展运算符(...)来减少代码,如下所示:

let apples = ['??', '??'];
let fruits = ['??', '??', '??', ...apples]; 
console.log( fruits ); //结果: ["??", "??", "??", "??", "??"]

16. 合并数组(在开头位置)

☘️ 普通写法

假设我们想将apples数组中的所有项添加到Fruits数组的开头,而不是像上一个示例中那样放在末尾。我们可以使用Array.prototype.unshift()来做到这一点:

let apples = ['??', '??'];
let fruits = ['??', '??', '??'];
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits ); //结果:["??", "??", "??", "??", "??"]

现在红苹果和绿苹果会在开头位置合并而不是末尾。

☘️ 简写方法

我们依然可以使用ES6扩展运算符(...)缩短这段长代码,如下所示:

let apples = ['??', '??'];
let fruits = [...apples, '??', '??', '??']; 

console.log( fruits ); //结果:["??", "??", "??", "??", "??"]

17. 克隆数组

☘️ 普通写法

我们可以使用Array中的slice()方法轻松克隆数组,如下所示:

let fruits = ['??', '??', '??', '??'];
let cloneFruits = fruits.slice();
console.log(cloneFruits); // ["??", "??", "??", "??"]
☘️ 简写方法

我们可以使用ES6扩展运算符(...)像这样克隆一个数组:

let fruits = ['??', '??', '??', '??'];
let cloneFruits = [...fruits];
console.log(cloneFruits); // ["??", "??", "??", "??"]

18. For循环

☘️ 普通写法

我们可以使用for循环像这样循环遍历一个数组:

let fruits = ['??', '??', '??', '??'];
// Loop through each fruit
for (let index = 0; index < fruits.length; index++) {
    console.log(fruits[index]); 
}

//结果:
// ??
// ??
// ??
// ??
☘️ 简写方法

我们可以使用for...of语句实现相同的结果,而代码要少得多,如下所示:

let fruits = ['??', '??', '??', '??'];
// Using for...of statement
for (let fruit of fruits) {
    console.log(fruit);
}

//结果:
// ??
// ??
// ??
// ??

19. 箭头函数

☘️ 普通写法

要遍历数组,我们还可以使用Array中的forEach()方法。但是需要写很多代码,虽然比最常见的for循环要少,但仍然比for...of语句多一点:

let fruits = ['??', '??', '??', '??'];
// Using forEach method
fruits.forEach(function (fruit) {
    console.log(fruit);
});

//结果:
// ??
// ??
// ??
// ??
☘️ 简写方法

但是使用箭头函数表达式,允许我们用一行编写完整的循环代码,如下所示:

let fruits = ['??', '??', '??', '??'];
fruits.forEach(fruit => console.log(fruit)); 
//结果: // ?? // ?? // ?? // ??

大多数时候我使用的是带箭头函数的forEach循环,这里我把for...of语句和forEach循环都展示出来,方便大家根据自己的喜好使用代码。

20. 在数组中查找对象

☘️ 普通写法

要通过其中一个属性从对象数组中查找对象的话,我们通常使用for循环:

let inventory = [
    { name: 'Bananas', quantity: 5 },
    { name: 'Apples', quantity: 10 },
    { name: 'Grapes', quantity: 2 }
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
    for (let index = 0; index < arr.length; index++) {
        // Check the value of this object property `name` is same as 'Apples'
        if (arr[index].name === 'Apples') { //=> ??
            // A match was found, return this object
            return arr[index];
        }
    }
}
let result = getApples(inventory);
console.log(result)
//结果:{ name: "Apples", quantity: 10 }
☘️ 简写方法

上面我们写了这么多代码来实现这个逻辑。但是使用Array中的find()方法和箭头函数=>,允许我们像这样一行搞定:

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
    return arr.find(obj => obj.name === 'Apples');
}

let result = getApples(inventory);
console.log(result)
//结果:{ name: "Apples", quantity: 10 }

21. 短路求值

☘️ 普通写法

如果我们必须根据另一个值来设置一个值不是falsy值,一般会使用if-else语句,就像这样:

function getUserRole(role) {
    let userRole;
    // If role is not falsy value
    // set `userRole` as passed `role` value
    if (role) {
        userRole = role;
    } else {
        // else set the `userRole` as USER
        userRole = 'USER';
    }
    return userRole;
}

console.log(getUserRole()) //=> "USER"
console.log(getUserRole('ADMIN')) //=> "ADMIN"
☘️ 简写方法

但是使用短路求值(||),我们可以用一行代码执行此操作,如下所示:

function getUserRole(role) {
    return role || 'USER'; // <-- here
}
console.log(getUserRole()) //=> "USER"
console.log(getUserRole('ADMIN')) //=> "ADMIN"

基本上,expression1 || expression2被评估为真表达式。因此,这就意味着如果第一部分为真,则不必费心求值表达式的其余部分。

posted on 2024-09-27 16:57  梁飞宇  阅读(35)  评论(0)    收藏  举报