JS小技巧

79 阅读1分钟
  1. 声明和初始化数组 我们可以使用默认值(如""、null或 )初始化特定大小的数组0。您可能已经将这些用于一维数组,但如何初始化二维数组/矩阵呢?

     //  fill给数组填充一个默认值
    const array = Array(5).fill("");
    // console.log(array);
    const matrix = Array(5)
        .fill(0)
        .map(() => Array(5).fill(0));
    console.log(matrix);
    
  2. 找出总和、最小值和最大值 我们应该利用reduce方法来快速找到基本的数学运算

     const array = [5, 4, 7, 8, 9, 2];
    console.log(
        "和",
        array.reduce((a, b) => a + b)
    ); //35
    console.log(
        "最大值",
        array.reduce((a, b) => (a > b ? a : b))
    );
    console.log(
        "最小值",
        array.reduce((a, b) => (a < b ? a : b))
    );
    
  3. 对字符串、数字或对象数组进行排序

    我们有内置的方法sort()和reverse()用于对字符串进行排序,但是数字或对象数组呢?

    让我们看看数字和对象的升序和降序排序技巧。

     //  排序字符串数组
    const arr = ["Joe", "Kapil", "Steve", "Musk"];
    arr.sort();
    //按照字母正序
    console.log(arr.sort());
    // 按照字母倒序
    console.log(arr.reverse());
    
    // 排序数字数组
    const array = [40, 100, 1, 5, 25, 10];
    
    console.log(
        "正序数组",
        array.sort((a, b) => a - b)
    );
    
    console.log(
        "倒序数组",
        array.sort((a, b) => b - a)
    );
    
    // 对象数数组排序
    const objectArr = [
        { first_name: "Lazslo", last_name: "Jamf" },
        { first_name: "Pig", last_name: "Bodine" },
        { first_name: "Pirate", last_name: "Prentice" },
    ];
    
    console.log(
        "对象数组排序",
        objectArr.sort((a, b) => a.first_name.localeCompare(b.first_name))
    );
    
    
  4. 从数组中过滤出虚假值

    const arr = [3, 0, 6, 7, "", false];
    
    console.log(arr.filter((item) => typeof item == "string"));
    
    console.log(typeof "");