1. 数组去重
const numbers =[1, 1, 1, 2, 3, 2, 4] let array = Array.from(new Set(numbers)); console.log(array); // Result: [1, 2, 3, 4] 或 let array = [...new Set(numbers)]; console.log(array); // Result: [1, 2, 3, 4] //数组对象去重 let person = [ {id: 0, name: "小明"}, {id: 1, name: "小张"}, {id: 2, name: "小李"}, {id: 3, name: "小孙"}, {id: 1, name: "小周"}, {id: 2, name: "小陈"}, ]; let obj = {}; let peon = person.reduce((cur,next) => { obj[next.id] ? "" : obj[next.id] = true && cur.push(next); return cur; },[]) //设置cur默认类型为数组,并且初始值为空的数组 console.log(peon); // (4) [{…}, {…}, {…}, {…}]0: {id: 0, name: "小明"}1: {id: 1, name: "小张"}2: {id: 2, name: "小李"}3: {id: 3, name: "小孙"}length: 4__proto__: Array(0) 或 let hash = {}; let config = [{ name: 2, state: true, output: 'Y', }, { name: 3, state: true, output: 'A', }, { name: 5, state: true, output: 'S', }, { name: 7, state: true, output: 'B', }]; config = [...config, { name: 3, state: false, output: 'A', }] const newArr = config.reduceRight((item, next) => { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []); console.log(JSON.stringify(newArr)); // [{"name":3,"state":false,"output":"A"},{"name":7,"state":true,"output":"B"},{"name":5,"state":true,"output":"S"},{"name":2,"state":true,"output":"Y"}]
2. 数组求和
const arr = [1,2,3,4,5,6,7] const sum = arr.reduce((pre,cur)=>{ return pre +cur }) console.log(sum) //Result:28
const arraySum = (arr) => arr.reduce((acc, val) => acc + val, 0);
3. 获取一个随机布尔值 (true/false)
const randomBoolean = () => Math.random() >= 0.5; console.log(randomBoolean()); // Result: a 50/50 change on returning true of false
4. 检查日期是否为工作日
const isWeekday = (date) => date.getDay() % 6 !== 0; console.log(isWeekday(new Date(2021, 0, 11))); // Result: true (Monday) console.log(isWeekday(new Date(2021, 0, 10))); // Result: false (Sunday)
5. 反转字符串
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
6. 检查当前 Tab 页是否在前台
const isBrowserTabInView = () => document.hidden; isBrowserTabInView(); // Result: returns true or false depending on if tab is in view / focus
7. 检查数字是否为奇数
const isEven = num => num % 2 === 0; console.log(isEven(2)); // Result: true console.log(isEven(3)); // Result: false
8. 从日期中获取时间
const timeFromDate = date => date.toTimeString().slice(0, 8); console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // Result: "17:30:00" console.log(timeFromDate(new Date())); // Result: will log the current time
9. 保留小数点(非四舍五入)
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); // Examples toFixed(25.198726354, 1); // 25.1 toFixed(25.198726354, 2); // 25.19 toFixed(25.198726354, 3); // 25.198 toFixed(25.198726354, 4); // 25.1987 toFixed(25.198726354, 5); // 25.19872 toFixed(25.198726354, 6); // 25.198726
10. 检查元素当前是否为聚焦状态
const elementIsInFocus = (el) => (el === document.activeElement); elementIsInFocus(anyElement) // Result: will return true if in focus, false if not in focus
11. 检查浏览器是否支持触摸事件
const touchSupported = () => { ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch); } console.log(touchSupported()); // Result: will return true if touch events are supported, false if not
12. 检查当前用户是否为苹果设备
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform); console.log(isAppleDevice); // Result: will return true if user is on an Apple device
13. 滚动到页面顶部/底部/可见区域
1.可以使用 window.scrollTo() 平滑滚动到页面顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page
或
const scrollToTop = () => {window.scrollTo({ top: 0, left: 0, behavior: "smooth" });};
2.滚动到页面底部
如果知道文档的高度,也可以平滑滚动到页面底部
const scrollToBottom = () => {window.scrollTo({top: document.documentElement.offsetHeight,left: 0,behavior: "smooth",});};
或
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
3. 滚动元素到可见区域
const smoothScroll = (element) => {element.scrollIntoView({behavior: "smooth",});};
14. 获取所有参数平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); // Result: 2.5
15. 转换华氏度/摄氏度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32; //摄氏度转华氏度 const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9; // Examples celsiusToFahrenheit(15); // 59 celsiusToFahrenheit(0); // 32 celsiusToFahrenheit(-20); // -4 fahrenheitToCelsius(59); // 15 fahrenheitToCelsius(32); // 0
16. 将任何值转换成布尔值
使用双感叹号(!!)能将任何内容转换成布尔值 !!true // true !!2 // true !![] // true !!false // false !!0 // false !!" " // false
17. 扩展运算符
连接两个数组数组 const nums1 = [1,2,3] const nums2 = [4,5,6] newArray = [...nums1 ,...nums2 ] //[1,2,3,4,5,6] 也可以将值推送到数组 let numbers = [1,2,3] numbers = [...numbers , 4, 5] //[1,2,3,4,5]
const smallObj = {x: 1};const otherObj = object.assign(smallObj, {y: 2})
//或者
const smallObj = {x: 1};Cconst otherObj = {...smallObj, y: 2}
18. 检查一个项目是否存在于数组中
let arrs = [1,2,3]; const hasNumber = arrs.indexOf(1) > -1 //true 或 const hasNumbers = arrs.includes(1) //true
19. 避免使用长||检查多个条件链
const nums = 1 if(num == 1 || num == 2 || num == 3){ console.log('true') } 更简便方法 if([1,2,3].includes(num)){ console.log('true') }
20. 数组扁平化
多维数组=>一维数组 let arr = [1, [2, [3, [4, 5]]], 6]; let str = jsON.stringify(ary); 1.arr.flat(Infinity);//注意:flat和flatMap方法为ES2019(ES10)方法,目前还未在所有浏览器完全兼容。 2.str.replace(/(\[\]))/g, '').split(','); 3.str = str.replace(/(\[\]))/g, ''); str = '[' + str + ']'; var ary = jsON.parse(str);
21. 数字化整数
const DigitizeInt = n => [...`${n}`].map(i => parseInt(i));
DigitizeInt(4560) // [4, 5, 6, 0]
DigitizeInt(131) // [1,3,1]
22. 修剪空格
let string = " a b cd e "; let Trim = string.replace(/\s+/g, ''); console.log(Trim)
24. 筛选出有相同key的对象
let namelist = [{ name: 'mark', age: 15, hair: 'long' }, { name: 'tuwen', age: 16, hair: 'short' }, { name: 'xiaoming', age: 16, hair: 'short' }, { name: 'lilei', age: 15, hair: 'short' }, { name: 'hanmei', age: 17, hair: 'long' }] ES6 let map = new Map() namelist.forEach(item => { if (map.has(item.age)) { map.set(item.age, map.get(item.age).concat(item)) } else { map.set(item.age, [item]) } }) console.log(map) const [arr1, arr2, arr3] = [...map] 结果 arr_1 = [{ name: 'mark', age: 15, hair: 'long' }, { name: 'lilei', age: 15, hair: 'short' }] arr_2 = [{ name: 'tuwen', age: 16, hair: 'short' }, { name: 'xiaoming', age: 16, hair: 'short' }] arr_3 = [{ name: 'hanmei', age: 17, hair: 'long' }]
25. 可编辑属性 contenteditable
html 中大部分标签都是不可以编辑的,但是添加了 contenteditable 属性之后,标签会变成可编辑状态。
<div contenteditable="true"></div>
不过通过这个属性把标签变为可编辑状态后只有 input 事件,没有 change 事件。也不能像表单一样通过 maxlength 控制最大长度。
26.解决 ios audio 无法自动播放、循环播放的问题
ios 手机在使用 audio 或者 video 播放的时候,个别机型无法实现自动播放,可使用下面的代码 hack。
// 解决ios audio无法自动播放、循环播放的问题var music = document.getElementById( video );var state = 0;document.addEventListener( touchstart , function(){if(state==0){music.play();state=1;}}, false);document.addEventListener("WeixinJSBridgeReady", function () {music.play();}, false);//循环播放music.onended = function () {music.load();music.play();}
27.空值合并运算符
// Example 1 // Longhand let str = '' let finalStr if (str !== null && str !== undefined) { finalStr = 'default string' } else { finalStr = str } // Shorthand let str = '' let finaStr = str ?? 'default string' // '' // Example 2 // Longhand let num = null let actualNum if (num !== null && num !== undefined) { actualNum = num } else { actualNum = 0 } // Shorthand let num = null let actualNum = num ?? 0 // 0
28.可选链接
const obj = { x: { y: 1, z: 2 }, others: [ 'test', 'tested' ] } // Longhand if (obj.hasProperty('others') && others.length >= 2) { console.log('2nd value in others: ', obj.others[1]) } // Shorthand console.log('2nd value in others: ', obj.others?.[1]) // 'tested' console.log('3rd value in others: ', obj.others?.[2]) // undefined
29.Array.indexOf 使用按位运算符的简写
const arr = [10, 12, 14, 16] const realNum = 10 const fakeNum = 20 const realNumIndex = arr.indexOf(realNum) const noneNumIndex = arr.indexOf(fakeNum) // Longhand if (realNumIndex > -1) { console.log(realNum, ' exists!') } else if (realNumIndex === -1) { console.log(realNum, ' does not exist!') } if (noneNumIndex > -1) { console.log(fakeNum, ' exists!') } else if (noneNumIndex === -1) { console.log(fakeNum, ' does not exist!') } // Shorthand console.log(realNum + (~realNumIndex ? ' exists!' : ' does not exist!') console.log(fakeNum + (~noneNumIndex ? ' exists!' : ' does not exist!')
30.双位非运算符
// Longhand const num = 4.5 const floorNum = Math.floor(num) // 4 // Shorthand const num = 4.5 const floorNum = ~~num // 4
31.指数幂速记
// Longhand const num = Math.pow(3, 4) // 81 // Shorthand const num = 3 ** 4 // 81
32.全屏退出和展示
//1.全屏显示元素 const goToFullScreen = (element) => { element = element || document.body; if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullScreen(); } }; //2.退出浏览器全屏状态 const goExitFullscreen = () => { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } };
33.获取数据类型
const getType = (value) => { const match = Object.prototype.toString.call(value).match(/ (\w+)]/) return match[1].toLocaleLowerCase() } getType() // undefined getType({}}) // object getType([]) // array getType(1) // number getType('fatfish') // string getType(true) // boolean getType(/fatfish/) // regexp
34.停止冒泡事件
const stopPropagation = (event) => { event = event || window.event; if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } };
35.确定设备类型
const isMobile = () => { return !!navigator.userAgent.match( /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i ); };
36.判断设备是Android还是ios
const isAndroid = () => { return /android/i.test(navigator.userAgent.toLowerCase()); }; const isIOS = () => { let reg = /iPhone|iPad|iPod|iOS|Macintosh/i; return reg.test(navigator.userAgent.toLowerCase()); };
37.获取浏览器类型及其版本
const getExplorerInfo = () => { let t = navigator.userAgent.toLowerCase(); return 0 <= t.indexOf("msie") ? { //ie < 11 type: "IE", version: Number(t.match(/msie ([\d]+)/)[1]), } : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11 type: "IE", version: 11, } : 0 <= t.indexOf("edge") ? { type: "Edge", version: Number(t.match(/edge\/([\d]+)/)[1]), } : 0 <= t.indexOf("firefox") ? { type: "Firefox", version: Number(t.match(/firefox\/([\d]+)/)[1]), } : 0 <= t.indexOf("chrome") ? { type: "Chrome", version: Number(t.match(/chrome\/([\d]+)/)[1]), } : 0 <= t.indexOf("opera") ? { type: "Opera", version: Number(t.match(/opera.([\d]+)/)[1]), } : 0 <= t.indexOf("Safari") ? { type: "Safari", version: Number(t.match(/version\/([\d]+)/)[1]), } : { type: t, version: -1, }; };
38.cookie设置 获取 删除
//1.设置cookie const setCookie = (key, value, expire) => { const d = new Date(); d.setDate(d.getDate() + expire); document.cookie = `${key}=${value};expires=${d.toUTCString()}`; }; //2.获取cookies const getCookie = (key) => { const cookieStr = unescape(document.cookie); const arr = cookieStr.split("; "); let cookieValue = ""; for (let i = 0; i < arr.length; i++) { const temp = arr[i].split("="); if (temp[0] === key) { cookieValue = temp[1]; break; } } return cookieValue; }; //3.删除cookies const delCookie = (key) => { document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`; };
39.生成随机字符串
const randomString = (len) => { let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789"; let strLen = chars.length; let randomStr = ""; for (let i = 0; i < len; i++) { randomStr += chars.charAt(Math.floor(Math.random() * strLen)); } return randomStr; }; randomString(10) // pfkMfjEJ6x randomString(20) // ce6tEx1km4idRNMtym2S
40.将字符串的第一个字母大写
const fistLetterUpper = (str) => { return str.charAt(0).toUpperCase() + str.slice(1); }; fistLetterUpper('fatfish') // Fatfish
或
const capitalizeWords = (str) => str.replace(/\b\w/g, char => char.toUpperCase());
41.生成指定范围内的随机数
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; randomNum(1, 10) // 6 randomNum(10, 20) // 11
42.打乱数组的顺序
const shuffleArray = (array) => { return array.sort(() => 0.5 - Math.random()) } let arr = [ 1, -1, 10, 5 ] shuffleArray(arr) // [5, -1, 10, 1] shuffleArray(arr) // [1, 10, -1, 5]
43.从数组中获取随机值
const getRandomValue = array => array[Math.floor(Math.random() * array.length)]; const prizes = [ '$100', '🍫', '🍔' ] getRandomValue(prizes) // 🍫 getRandomValue(prizes) // 🍔 getRandomValue(prizes) // 🍫
44.查找数组中的最大值
const maxNumber = (arr) => Math.max(...arr);
45.检查字符串是否为回文
const isPalindrome = (str) => str === str.split('').reverse().join('');
46.生成随机十六进制颜色
const randomHexColor = () => `#${Math.floor(Math.random()*16777215).toString(16)}`;
47.打乱数组,随机排序
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
48.查找两个数组的交集
const arrayIntersection = (arr1, arr2) => arr1.filter(value => arr2.includes(value));
49.获取数组中的最后一项
const getLastItem = (arr) => arr.slice(-1)[0];
50.计算数组中某个值的出现次数
const countOccurrences = (arr, value) => arr.reduce((acc, cur) => (cur === value ? acc + 1 : acc), 0);
51.从数组中删除假值
const removeFalsyValues = (arr) => arr.filter(Boolean);
52.检查对象是否为空
const isObjectEmpty = (obj) => Object.keys(obj).length === 0;
或
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}); // true
isEmpty({a: "not empty"}); // false
53.查找两个数组之间的差异
const arrayDifference = (arr1, arr2) => arr1.filter(value => !arr2.include
54.ES6对象删除属性的方法
let obj = { name: 'Alice', age: '18' }console.log(obj) // {name: 'Alice', age: '18'}console.log(Reflect.deleteProperty(obj, 'age')) // trueconsole.log(obj) // {name: 'Alice'}
55.ES6和原生 数组去重
1. filter() 方法配合 indexOf()
const uniqueArray = array.filter((item, index, self) => {
return self.indexOf(item) === index;
});
该方法利用 filter() 遍历数组,对于每个元素,通过 indexOf() 查找其在原数组中的第一个索引。如果当前元素的索引与正在遍历的索引相同,说明这是该元素在数组中的首次出现,保留该元素;否则,忽略该元素。
2. reduce() 方法
const uniqueArray = array.reduce((acc, current) => {
return acc.includes(current) ? acc : [...acc, current];
}, []);
这里使用 reduce() 函数将数组累积到一个新的数组(acc)中。在每次迭代中,检查当前元素是否已存在于累积数组中。若不存在,则将其添加至累积数组;否则,跳过该元素。
3. 使用扩展运算符与解构赋值
const uniqueArray = [...new Set(array)];
这种方法简洁高效,利用 ES6 的 Set 数据结构自动去除重复元素的特性,再通过扩展运算符将 Set 转换回数组。Set 是一种特殊的集合,不允许重复元素存在,因此插入过程会自动过滤重复项。
4. 利用 Map 数据结构
const uniqueArray = Array.from(new Map(array.map(item => [item, item])).values());
尽管不如直接使用 Set 直观,但此方法同样有效。它首先将数组映射为键值对相同的 Map,由于 Map 键的唯一性,重复的数组元素会被自动忽略。然后通过 Array.from() 和 Map.values() 将 Map 的值(即无重复元素)转换回数组。
56.检查是否为函数
const isFunction = (obj) => typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function";
57. 从 URL 获取参数并转换为对象
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
58. 进制转换
const num = 10;
num.toString(2); // 输出: "1010"
num.toString(16); // 输出: "a"
num.toString(8); // 输出: "12"
59. ||= 和 ??=:条件赋值
||=仅在左侧为假值时赋值,而??=仅在左侧为null或undefined时赋值:
let x = null;
x ||= 5; // 输出: 5
let y = 10;
y ||= 7; // 输出: 10
let a = null;
a ??= 5; // 输出: 5
let b = 10;
b ??= 7; // 输出: 10
60. 并集、交集和差集
使用Set对象可以方便地进行数组的并集、交集和差集操作:
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]); // Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x))); // Set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x))); // Set {1}
61. 声明和初始化数组
const array = Array(5).fill(''); // ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(() => Array(5).fill(0));
// [Array(5), Array(5), Array(5), Array(5), Array(5)]
// 0: (5) [0, 0, 0, 0, 0]
// 1: (5) [0, 0, 0, 0, 0]
// ...
// length: 5
62. 快速取整
// 传统写法
const floor = Math.floor(3.7);
// 简写方式
const floor = ~~3.7;
63. 短路求值
// 传统写法
if (condition) {
doSomething();
}
// 简写方式
condition && doSomething();
64. 动态对象属性
// 传统写法
const obj = {};
obj[dynamic + 'name'] = value;
// 简写方式
const obj = {
[`${dynamic}name`]: value
};
65. Set对象新方法
1. Intersection():寻找共同点
const setA = new Set([1, 2, 3, 4]);const setB = new Set([3, 4, 5, 6]);const intersection = setA.intersection(setB);// Expected output: Set {3, 4}
2. union():联合力量
const setA = new Set([1, 2, 3]);const setB = new Set([3, 4, 5]);const unionSet = setA.union(setB);
// Expected output: Set {1, 2, 3, 4, 5}
3. difference():找出唯一性
const setA = new Set([1, 2, 3]);const setB = new Set([3, 4, 5]);const differenceSetA = setA.difference(setB);// Expected output: Set {1, 2}const differenceSetB = setB.difference(setA);// Expected output: Set {4, 5}
4. symmetricDifference():突出差异
const setA = new Set([1, 2, 3]);const setB = new Set([3, 4, 5]);const symmetricDifferenceSetA = setA.symmetricDifference(setB);// Expected output: Set {1, 2, 4, 5}const symmetricDifferenceSetB = setB.symmetricDifference(setA);// Expected output: Set {4, 5, 1, 2}
5. isSubsetOf():检查包含性
const setA = new Set([2, 3]);const setB = new Set([1, 2, 3, 4]);const isSubset = setA.isSubsetOf(setB);// Expected output: true
6. isSupersetOf():逆关系
const setA = new Set([1, 2, 3, 4]);const setB = new Set([2, 3]);const isSuperset = setA.isSupersetOf(setB);
// Expected output: true
7. isDisjointFrom():识别分离
const setA = new Set([1, 2]);const setB = new Set([3, 4]);const setC = new Set([4, 5]);const areDisjoint1 = setA.isDisjointFrom(setB);// Expected output: trueconst areDisjoint2 = setB.isDisjointFrom(setC);// Expected output: false