一些在前端项目中会用到的快捷操作,下面的代码都可以直接复制到控制台运行。
数字取整
- let floatNum = 100.5;
- let intNum = ~~floatNum;
- console.log(intNum); // 100
字符串转数字
- let str="10000";
- let num = +str;
- console.log(num); // 10000
Falsy和Truthy值转boolean
Falsy为Javascript中所有可以转换为false的值的统称,共8个:false本身、空字符串、null、undefined、NaN、数字0、数字-0、大数字0n。
除Falsy值外其他所有值都是Truthy
- let falseNum = 0;
- let falseStr = "";
- let falseUndefined;
- let falseNull = null;
- let falseNaN = 0/0;
- let trueNum = 1;
- let trueStr = "何方";
- let trueObj = {name:"何方"};
- let trueArr = ["前端","后端"];
- console.log("falseNum", !!falseNum); // false
- console.log("falseStr", !!falseStr); // false
- console.log("falseUndefined", !!falseUndefined); // false
- console.log("falseNaN",!!falseNaN); // false
- console.log("trueNum",!!trueNum); // true
- console.log("trueStr",!!trueStr); // true
- console.log("trueObj",!!trueObj); // true
- console.log("trueArr",!!trueArr); // true
交换对象键值
- let obj = {
- key1: "value1",
- key2: "value2"
- };
- let revert = {};
- Object.entries(obj).forEach(([key, value]) => revert[value] = key);
- console.log(revert);
数组去重
值类型数组
- let arrNum = [
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
- ];
- let arrString = [
- "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
- "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"
- ];
- let arrMixed = [
- 1, "1", "2", true, false, false, 1, 2, "2"
- ];
- arrNum = Array.from(new Set(arrNum));
- arrString = [...new Set(arrString)];
- arrMixed = [...new Set(arrMixed)];
- console.log(arrNum); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
- console.log(arrString); // ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
- console.log(arrMixed); // [1, "1", "2", true, false, 2]
引用类型数组
- let arrObj = [
- {name: "何方"},
- {name: "王二"},
- {name: "何方"},
- {name: "何方"},
- {name: "何方"},
- {name: "何方"},
- {name: "王二"},
- {name: "王二"},
- {name: "王二"},
- {name: "王二"},
- ];
- let arrObj2 = [];
- arrObj.forEach(item => {
- arrObj2.find(find => find.name === item.name) || arrObj2.push(item)
- });
- console.log(arrObj2);