字符串、函数、数组和对象的扩展

114 阅读1分钟

1. 字符串扩展

  • 模板字符串:使用反引号(``)来定义字符串,可以包含变量、表达式以及多行字符串。

    const name = "Alice";
    const greeting = `Hello, ${name}!`;
    console.log(greeting); // Hello, Alice!
    
  • includes() :判断字符串是否包含指定的子字符串,返回布尔值。

    const str = "Hello, world!";
    console.log(str.includes("world")); // true
    
  • startsWith()endsWith() :判断字符串是否以指定的子字符串开始或结束。

    console.log(str.startsWith("Hello")); // true
    console.log(str.endsWith("!")); // true
    
  • padStart()padEnd() :在字符串的开始或结束填充指定的字符,直到达到指定的长度。

    const str = "5";
    console.log(str.padStart(3, "0")); // 005
    console.log(str.padEnd(3, "0"));   // 500
    

2. 函数扩展

  • 箭头函数:简化了函数表达式,且没有自己的 this,它继承自外部函数的 this

    const sum = (a, b) => a + b;
    console.log(sum(2, 3)); // 5
    
  • 参数默认值:在函数参数中可以设置默认值,如果没有传入参数则使用默认值。

    function greet(name = "Guest") {
      console.log(`Hello, ${name}`);
    }
    greet(); // Hello, Guest
    greet("Alice"); // Hello, Alice
    
  • 剩余参数:使用 ...args 将不定数量的参数收集为一个数组。

    function sum(...args) {
      return args.reduce((acc, curr) => acc + curr, 0);
    }
    console.log(sum(1, 2, 3)); // 6
    

3. 数组扩展

  • 扩展运算符(... :用于展开数组或对象,常用于函数参数传递和数组复制。

    const arr = [1, 2, 3];
    const newArr = [...arr, 4, 5];
    console.log(newArr); // [1, 2, 3, 4, 5]
    
  • find()findIndex()find() 返回第一个符合条件的元素,findIndex() 返回符合条件的元素的索引。

    const arr = [1, 2, 3, 4];
    console.log(arr.find(x => x > 2)); // 3
    console.log(arr.findIndex(x => x > 2)); // 2
    
  • flat() :将多维数组“扁平化”成一维数组。

    const arr = [1, [2, 3], [4, 5]];
    console.log(arr.flat()); // [1, 2, 3, 4, 5]
    

4. 对象扩展

  • 属性简写:当对象属性名和变量名相同,可以省略属性值。

    const x = 1, y = 2;
    const obj = { x, y };
    console.log(obj); // { x: 1, y: 2 }
    
  • 计算属性名:使用表达式作为对象的属性名。

    const key = "name";
    const obj = { [key]: "Alice" };
    console.log(obj.name); // Alice
    
  • Object.assign() :用于将源对象的所有可枚举属性复制到目标对象。

    const obj1 = { a: 1, b: 2 };
    const obj2 = { b: 3, c: 4 };
    const merged = Object.assign({}, obj1, obj2);
    console.log(merged); // { a: 1, b: 3, c: 4 }