数组

作者: 白小纯Zzz | 来源:发表于2018-11-21 08:44 被阅读0次
    1.清空或截断数组
          在不重新给数组赋值的情况下,清空或截断数组的最简单方法是更改​​其 length 属性值:
    
          const arr = [11, 22, 33, 44, 55, 66];
          // truncanting
          arr.length = 3;
          console.log(arr); //=> [11, 22, 33]
          // clearing
          arr.length = 0;
          console.log(arr); //=> []
          console.log(arr[2]); //=> undefined
    
    2.从数组中删除重复元素(数组去重)
          通过使用通过使用集合语法和 Spread(展开)运算符,您可以轻松地从数组中删除重复项:\
    
          const removeDuplicateItems = arr => [...new Set(arr)];
          removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
          //=> [42, "foo", true]
          
          const arr = [42, 'foo', 42, 'foo', true, true]
          console.log([...new Set(arr)];)
    
    3.平铺多维数组
          使用 Spread(展开),可以很容易去平铺嵌套多维数组:
      
          const arr = [11, [22, 33], [44, 55], 66];
          const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
    
          可惜,上面的方法仅仅适用于二维数组。不过,通过递归,我们可以平铺任意维度的嵌套数组。
    
          unction flattenArray(arr) {
              const flattened = [].concat(...arr);
              return flattened.some(item => Array.isArray(item)) ? 
              flattenArray(flattened) : flattened;
          }
              const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
              const flatArr = flattenArray(arr); 
              //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
    
    4.创建纯(pure)对象
              您可以创建一个 100% 纯对象,它不会从 Object 继承任何属性或方法(例如,constructor,toString() 等)。
    
              const pureObject = Object.create(null);
              console.log(pureObject); //=> {}
              console.log(pureObject.constructor); //=> undefined
              console.log(pureObject.toString); //=> undefined
              console.log(pureObject.hasOwnProperty); //=> undefined
    
    5.使用 async/await 来 await多个async函数
              可以使用 Promise.all 来 await 多个 async(异步)函数。
    
              await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
    
    6.使用对象解构来处理数组
              可以使用对象解构将数组项分配给各个变量:
    
              const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
              const { 2: country, 4: state } = csvFileLine.split(',');

    相关文章

      网友评论

          本文标题:数组

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