字符串排序
const arr=[{name:'ccc'},{name:'bbb'},{name:'ccc'}]
arr.sort((a,b)=>a.name.localeCompare(b.name))
从数组中过滤出虚假值
const arr=[1,2,'',undefined]
const arr1 = arr.filter(v=>v) //[1,2]
删除重复值
const arr=[1,2,1,3]
const arr1 = [...new Set(arr)] //[1,2,3]
创建计数器对象或映射
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
打乱数组
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;
// 输出: 0
Rest & 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"]
默认参数
const search = (arr, low=0,high=arr.length-1) => {return high;
}
search([1,2,3,4,5]);// 输出: 4
将十进制转换为二进制或十六进制
const num = 10;num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"
使用解构赋值交换值
let a = 5;
let b = 8;
[a,b] = [b,a][a,b]
// 输出
(2) [8, 5]
Object属性转成属性数组
使用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]
当有多个参数的时候需要获取event默认参数
function eventTest(a,b){var event = window.event || arguments.callee.caller.arguments[0]//target 就是这个对象target = event.srcElement||event.target,//这个对象的值targetValue = event.target.value;
}
清空对象的值(两种办法)
场景:表单填写,提交之后表单中的数据清空。
- 第一种for in
let obj = {a:1,b:2};
for(let key in obj){obj[key]='';
}
- 第二种处理对象之前提前存一条(需要深拷贝)
let obj1=JSON.parse(JSON.stringify(obj))
// 之后就push数据
obj=obj1