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

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

文章目录

备注:以下东西都可以用
export const + 变量 导出去,然后用
require去引用!

数组去重
// 方式1var fruits1 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];var uniqueFruits1 = Array.from(new Set(fruits1))console.log(uniqueFruits1)//["banana", "apple", "orange", "watermelon", "grape"]// 方式2var uniqueFruits2 = [...new Set(fruits1)]console.log(uniqueFruits2)// ["banana", "apple", "orange", "watermelon", "grape"]// 方式3var uniqueFruits3 = [];fruits1.forEach(element => {     if(uniqueFruits3.indexOf(element) === -1) {       uniqueFruits3.push(element)  }});console.log(uniqueFruits3)// 方式4var uniqueFruits4 = [];fruits1.forEach((element) => {     if(!uniqueFruits4.includes(element)){       uniqueFruits4.push(element)  }})console.log(uniqueFruits4)
数组扁平化

此法利用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]]]);
将一维数组分割为二维
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到末尾
// 1203040506 -> 1234560000移动数字到末尾    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));
替换特定的值
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)
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}    ];// 方式1var friendName1 = friends1.map((item) => {     return item.name})console.log(friendName1)// ["John", "Peter", "Mark", "Maria", "Monica", "Martha"]// 方式2var friendName2 = Array.from(friends1, ({   name}) => name)console.log(friendName2)// ["John", "Peter", "Mark", "Maria", "Monica", "Martha"]
转成空数组
var fruits3 = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];fruits3.length = 0console.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"}
填充数组
var newArray = new Array(10).fill('520')console.log(newArray)// ["520", "520", "520", "520", "520", "520", "520", "520", "520", "520"]
合并数组
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"]// 或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]

备注:Array.prototype.includes()

// includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。let arr = [20,29,44,-4,52,205]console.log(arr.includes(20,1))// falseconsole.log(arr.includes(20,0)) // trueconsole.log(arr.includes(20)) // true
用过滤从数组中删除假值,保留真值
var mixedArr = [0, NaN, 9, false, undefined, '', 'black']var trueArr = mixedArr.filter(Boolean)// 等价于array.filter((item) => {return Boolean(item)})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"}

JSON.stringify 会有很多的坑,详见[https://mp.weixin.qq.com/s/jmEXKuamwP6EgfntuvV9fQ]

对象里的值相加
let obj = [      {           a: 1,        b: 2      },      {           a: 3,        b: 4      },      {           c: 5,        b: 2      },      {           c: 1,        d: 4,        f: 6      }    ]    // 输出:    // {       //   a: 4,    //   b: 8,    //   c: 6,    //   d: 4    // }    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)
利用reduce将数组转为对象,且将其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, …}
通过递归的方式返回父级节点

应用场景: 删除父级节点(包括父级)以下所有节点内容

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];          // nodeKey是因为每级菜单都有nodeKey这个键          if (currentNode.nodeKey === node.nodeKey) {               // 没有parent说明在一级菜单上            if (!currentNode.parent) {                 // 删除字节点上的parent属性              // deleteKey(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个
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/

你可能感兴趣的文章
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB可视化客户端管理工具之NoSQLbooster4mongo
查看>>
Mongodb学习总结(1)——常用NoSql数据库比较
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
mongodb定时备份数据库
查看>>
mppt算法详解-ChatGPT4o作答
查看>>
mpvue的使用(一)必要的开发环境
查看>>
MQ 重复消费如何解决?
查看>>
mqtt broker服务端
查看>>
MQTT 保留消息
查看>>
MQTT 持久会话与 Clean Session 详解
查看>>
MQTT工作笔记0007---剩余长度
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
Mqtt搭建代理服务器进行通信-浅析
查看>>
MS Edge浏览器“STATUS_INVALID_IMAGE_HASH“兼容性问题
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>
MSBuild 教程(2)
查看>>
msbuild发布web应用程序
查看>>
MSB与LSB
查看>>