实用js片段
字符串排序
const arr=[{name:'ccc'},{name:'bbb'},{name:'ccc'}] arr.sort((a,b)=>a.name.localeCompare(b.name))從數(shù)組中過濾出虛假值
const arr=[1,2,'',undefined] const arr1 = arr.filter(v=>v) //[1,2]刪除重復(fù)值
const arr=[1,2,1,3] const arr1 = [...new Set(arr)] //[1,2,3]創(chuàng)建計數(shù)器對象或映射
let string = 'kapilalipak';const table = {};for (let char of string) {table[char] = table[char] + 1 || 1;} // 輸出{ k: 2, a: 3, p: 2, i: 2, l: 2 } //或者 const countMap = new Map();for (let i = 0; i < string.length; i++) {if (countMap.has(string[i])) {countMap.set(string[i], countMap.get(string[i]) + 1);} else {countMap.set(string[i], 1);}} // 輸出 Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}可選鏈
const user = {employee: {name: "Kapil"} }; user.employee?.name; // 輸出: "Kapil" user.employ?.name; // 輸出: undefined user.employ.name // 輸出: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined打亂數(shù)組
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; list.sort(() => {return Math.random() - 0.5; }); // 輸出 (9) [2, 5, 1, 6, 9, 8, 4, 3, 7] // Call it again (9) [4, 1, 7, 5, 3, 8, 2, 9, 6]空合并算子
const foo = null ?? 'my school'; // 輸出: "my school"const baz = 0 ?? 42; // 輸出: 0Rest & Spread 運算符
function myFun(a, b, ...manyMoreArgs) {return arguments.length; } myFun("one", "two", "three", "four", "five", "six");// 輸出: 6 const parts = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; lyrics; // 輸出: (5) ["head", "shoulders", "knees", "and", "toes"]默認(rèn)參數(shù)
const search = (arr, low=0,high=arr.length-1) => {return high; } search([1,2,3,4,5]);// 輸出: 4將十進(jìn)制轉(zhuǎn)換為二進(jìn)制或十六進(jìn)制
const num = 10;num.toString(2); // 輸出: "1010" num.toString(16); // 輸出: "a" num.toString(8); // 輸出: "12"使用解構(gòu)賦值交換值
let a = 5; let b = 8; [a,b] = [b,a][a,b] // 輸出 (2) [8, 5]Object屬性轉(zhuǎn)成屬性數(shù)組
使用Object.entries(),Object.keys()和Object.values() const obj = { a: 1, b: 2, c: 3 };Object.entries(obj); // 輸出 (3) [Array(2), Array(2), Array(2)] 0: (2) ["a", 1] 1: (2) ["b", 2] 2: (2) ["c", 3] length: 3Object.keys(obj); (3) ["a", "b", "c"]Object.values(obj); (3) [1, 2, 3]當(dāng)有多個參數(shù)的時候需要獲取event默認(rèn)參數(shù)
function eventTest(a,b){var event = window.event || arguments.callee.caller.arguments[0]//target 就是這個對象target = event.srcElement||event.target,//這個對象的值targetValue = event.target.value; }清空對象的值(兩種辦法)
場景:表單填寫,提交之后表單中的數(shù)據(jù)清空。
- 第一種for in
- 第二種處理對象之前提前存一條(需要深拷貝)
總結(jié)
- 上一篇: 用了同层排水,卫生间就不会堵和臭了吗?吉
- 下一篇: 欧派木门厂家是哪里的?