美文网首页
30S学习javascript

30S学习javascript

作者: 怪兽别跑biubiubi | 来源:发表于2018-03-26 10:09 被阅读0次

    数组

    返回数组中的最大值.

    Math.max()与扩展运算符 (...) 结合使用以获取数组中的最大值。

    返回数组中的最小值。

    Math.min()与扩展运算符 (...) 结合使用以获取数组中的最小值。

    <script>
    // ...  :扩展运算符
    // arrayMax
    const arrMax = arr => Math.max(...arr);
    console.log(arrMax([10,2,15,87,12,12]));   // 87
    // arrayMin
    const arrMin = arr => Math.min(...arr);
    console.log(arrMin([10,54,87,45,1,2,0,12]));      // 0   
    </script> 
    

    将数组块划分为指定大小的较小数组。·

    使用Array.from()创建新的数组, 这符合将生成的区块数。使用Array.slice()将新数组的每个元素映射到size长度的区块。如果原始数组不能均匀拆分, 则最终的块将包含剩余的元素。

    <script>
      const chunk = (arr, size) => 
      Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
      console.log(chunk([1,3,5,7,2,6], 3))    //  [1, 3, 5] ,  [7, 2, 6]
      console.log(chunk([1,3,5,7,2,6], 2))    //  [1, 3],[5, 7],[2, 6]
    </script>
    

    ◎Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
    ◎Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
    ◎Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。

    从数组中移除 falsey 值.

    使用Array.filter()筛选出 falsey 值 (falsenull0""undefinedNaN).

    <script>
      const compact = (arr) => arr.filter(Boolean);
      compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
    </script>
    

    计算数组中值的出现次数。

    使用Array.reduce()在每次遇到数组中的特定值时递增计数器。

    <script>
      const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
      countOccurrences([1,1,2,1,2,3], 1) -> 3
    </script>
    

    深拼合数组。

    <script>
      const chunk = (arr, size) => 
      Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
      console.log(chunk([1,3,5,7,2,6], 3))    //  [1, 3, 5] ,  [7, 2, 6]
      console.log(chunk([1,3,5,7,2,6], 2))    //  [1, 3],[5, 7],[2, 6]
    </script>
    

    相关文章

      网友评论

          本文标题:30S学习javascript

          本文链接:https://www.haomeiwen.com/subject/gcmlcftx.html