博客
关于我
js常用的工具库
阅读量:200 次
发布时间:2019-02-28

本文共 7444 字,大约阅读时间需要 24 分钟。

文章目录

  • 数组去重

    • 方式一
      // 使用Set去重并转为数组  
      var fruits1 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
      var uniqueFruits1 = Array.from(new Set(fruits1));
      console.log(uniqueFruits1);
      // ["banana", "apple", "orange", "watermelon", "grape"]
    • 方式二
      // 使用Spread运算  
      var uniqueFruits2 = [...new Set(fruits1)];
      console.log(uniqueFruits2);
      // ["banana", "apple", "orange", "watermelon", "grape"]
    • 方式三
      // 使用forEach遍历并添加  
      var uniqueFruits3 = [];
      fruits1.forEach(element => {
      if(uniqueFruits3.indexOf(element) === -1) {
      uniqueFruits3.push(element);
      }
      });
      console.log(uniqueFruits3);
      // ["banana", "apple", "orange", "watermelon", "grape"]
    • 方式四
      // 使用includes方法  
      var uniqueFruits4 = [];
      fruits1.forEach((element) => {
      if(!uniqueFruits4.includes(element)){
      uniqueFruits4.push(element);
      }
      });
      console.log(uniqueFruits4);
      // ["banana", "apple", "orange", "watermelon", "grape"]
  • 数组扁平化

    • 方法一
      // 利用concat方法递归扁平化  
      function flatten(arr) {
      while (arr.some((item) => Array.isArray(item))) {
      arr = [].concat(...arr);
      }
      return arr;
      }
      const newArr = flatten([1, 2, 3, [4, 5, 6, [7, 8, 9]]]);
      console.log(newArr);
      // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 将一维数组分割为二维

    • 代码示例
      // 定义分割函数  
      function changeArrGroup (arr, newArrLength) {
      let changeIndex = 0;
      let secondArr = [];
      while (changeIndex < arr.length) {
      secondArr.push(arr.slice(changeIndex, changeIndex += newArrLength));
      }
      return secondArr;
      }
      console.log(changeArrGroup([1,2,3,4,5,6,7,8,9],3));
      // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • 移动0到末尾

    • 代码示例
      // 移动0到尾部  
      function removeZero(nums){
      let num = nums.toString().split('');
      let n = 0;
      for(let i = 0; i < num.length; i++){
      if(num[i] != '0'){
      num[n] = num[i];
      n++;
      }
      }
      for(let k = n; k < num.length; k++){
      num[k] = '0';
      }
      return Number(num.join(''));
      }
      console.log(removeZero(102000003040500000006n));
      // 1234560000
  • 替换特定的值

    • 代码示例
      // 替换数组开头的两个元素  
      var fruits2 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
      fruits2.splice(0, 2, 'pitaya', 'mango');
      console.log(fruits2);
      // ["pitaya", "mango", "orange", "watermelon", "apple", "orange", "grape", "apple"]
  • 从对象映射出数组(map与Array.from)

    • 代码示例一
      // 使用map方法  
      var friends1 = [
      {name: 'John', age: 22},
      {name: 'Peter', age: 23},
      {name: 'Mark', age: 24},
      {name: 'Maria', age: 25},
      {name: 'Monica', age: 26},
      {name: 'Martha', age: 27}
      ];
      var friendName1 = friends1.map((item) => {
      return item.name;
      });
      console.log(friendName1);
      // ["John", "Peter", "Mark", "Maria", "Monica", "Martha"]
    • 代码示例二
      // 使用Array.from和对象展开  
      var friendName2 = Array.from(friends1, ({name}) => name);
      console.log(friendName2);
      // ["John", "Peter", "Mark", "Maria", "Monica", "Martha"]
  • 转成空数组

    • 代码示例
      // 通过设置长度为0  
      var fruits3 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
      fruits3.length = 0;
      console.log(fruits3);
      // []
  • 数组转化为对象

    • 代码示例
      // 使用对象展开操作符  
      var fruits4 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
      var fruits4Obj = {
      ...fruits4
      };
      console.log(fruits4Obj);
      // {0: "banana", 1: "apple", 2: "orange", 3: "watermelon", 4: "apple", 5: "orange", 6: "grape", 7: "apple"}
  • 填充数组

    • 代码示例
      // 创建长度为10的数组,全部填充'520'  
      var newArray = new Array(10).fill('520');
      console.log(newArray);
      // ["520", "520", "520", "520", "520", "520", "520", "520", "520", "520"]
  • 合并数组

    • 代码示例一
      // 使用concat方法  
      var fruit5 = ['banana', 'apple', 'orange', 'watermelon', 'grape'];
      var meat = ['poultry', 'beef', 'fish'];
      var vegetable = ['potato', 'tomato', 'cucumber'];
      var concat1 = fruit5.concat(meat);
      console.log(concat1);
      // ["banana", "apple", "orange", "watermelon", "grape", "poultry", "beef", "fish"]
    • 代码示例二
      // 使用spread运算合并多个数组  
      var food = [...fruit5, ...meat, ...vegetable];
      console.log(food);
      // ["banana", "apple", "orange", "watermelon", "grape", "poultry", "beef", "fish", "potato", "tomato", "cucumber"]
  • 求数组交集

    • 代码示例
      // 找出两个数组的交集  
      var numOne = [0,1,2,4,6,8,8];
      var numTwo = [1,2,3,8,8];
      var duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item));
      console.log(duplicatedValues);
      // [1, 2, 8]
  • 用过滤从数组中删除假值,保留真值

    • 代码示例
      // 过滤数组中的假值  
      var mixedArr = [0, NaN, 9, false, undefined, '', 'black'];
      var trueArr = mixedArr.filter(Boolean);
      console.log(trueArr);
      // [9, "black"]
  • 从数组中获取随机值

    • 代码示例
      // 随机获取数组中的一个元素  
      var fruit6 = ['banana', 'apple', 'orange', 'watermelon', 'grape'];
      var fruit6random = fruit6[Math.floor(Math.random() * (fruit6.length))];
      console.log(fruit6random);
      // "grape" 或者数组中的其他项
  • 获取月份天数

    • 代码示例
      // 获取指定年月的天数  
      function getMonthCountDay (year, month){
      return 32 - new Date(year, month-1, 32).getDate();
      }
  • 数据类型判断

    • 代码示例
      // 判断数据类型  
      function typeOf(obj) {
      const o = Object.prototype.toString.call(obj);
      return (
      o.match(/\s+(\w+)/)[1]
      .slice(0, 1)
      .toLocaleLowerCase() +
      o.match(/\s+(\w+)/)[1].slice(1)
      );
      }
      console.log(typeOf(123));
  • 通过JSON.stringify做对象筛选

    • 代码示例
      // 定义替换函数  
      const replaceFun = (key, value) => {
      console.log(key, value);
      if (key === 'name') {
      return undefined;
      }
      return value;
      };
      const myIntro = {
      name: 'han',
      age: 18,
      link: 'FE',
      };
      console.log(JSON.stringify(myIntro, replaceFun));
      // {"age":18,"link":"FE"}
  • 对象里的值相加

    • 代码示例
      // 遍历对象并累加  
      let obj = [
      {a: 1, b: 2},
      {a: 3, b: 4},
      {c: 5, b: 2},
      {c: 1, d: 4, f: 6}
      ];
      let newObj = {};
      for(let item of obj){
      for(let i in item){
      if(!newObj.hasOwnProperty(i)){
      newObj[i] = item[i];
      } else{
      newObj[i] += item[i];
      }
      }
      }
      console.log(newObj);
      // {a:4, b:8, c:6, d:4}
  • 利用reduce将数组转为对象,且将其value拼接为新对象

    • 代码示例
      // 将数组转为对象并拼接value  
      let user = [
      {name: '张三', age: 26},
      {name: '赵四', age: 27},
      {name: '李五', age: 28},
      {name: '王六', age: 29},
      {name: '周七', age: 30},
      {name: '李八', age: 31}
      ];
      let o = user.reduce((obj, item) => {
      return {
      ...obj,
      [item.name]: item.age
      };
      }, {});
      console.log(o);
      // {张三:26, 赵四:27, 李五:28, 王六:29, 周七:30, 李八:31}
  • 通过递归的方式返回父级节点

    • 代码示例
      // 递归删除父级节点及其子节点  
      let obj = [
      {
      name: '小王',
      age: 65,
      nodeKey: '1',
      children: [
      {
      name: '小李',
      age: 30,
      nodeKey: '1-1',
      children: [
      {
      name: '小胡',
      age: 6,
      nodeKey: '1-1-1'
      }
      ]
      },
      {
      name: '小白',
      age: 13,
      nodeKey: '1-2'
      }
      ]
      }
      ];
      const node = {
      name: '小胡',
      age: 6,
      nodeKey: '1-1-1'
      };
      const getNode = (arr, node) => {
      for (let i = 0; i < arr.length; i++) {
      const currentNode = arr[i];
      if (currentNode.nodeKey === node.nodeKey) {
      if (!currentNode.parent) {
      return currentNode;
      } else {
      return true;
      }
      } else {
      if (currentNode.children && currentNode.children.length > 0) {
      currentNode.children.map((o) => {
      o.parent = currentNode;
      });
      if (getNode(currentNode.children, node)) {
      return currentNode;
      }
      }
      }
      }
      };
      console.log(getNode(obj, node));
  • 10000个数取最大的10个

    • 代码示例
      // 生成10000个随机数并提取最大的10个  
      let arr = [];
      for(let i=0; i < 10000; i++){
      arr.push(Math.floor(Math.random()*10000));
      }
      console.log(arr);
      // 去重
      arr = Array.from(new Set(arr));
      console.log(arr);
      // 排序
      arr = arr.sort(function(a,b){
      return b-a;
      });
      console.log(arr);
      // 取前10个数
      max10Arr = arr.slice(0,10);
      console.log(max10Arr);

转载地址:http://ggni.baihongyu.com/

你可能感兴趣的文章
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>