33个有用的 JavaScript 小技巧

1、if
//longhandif (fruit === 'apple' || fruit === 'banana' || fruit === 'orange' || fruit ==='mango') {//logic}//shorthandif (['apple', 'banana', 'orange', 'mango'].includes(fruit)) {//logic}
2、 If... else 简写
当我们想使用 if-else 语句时,这个会对你有所帮助。当你使用 2-3 个 if.. else 时,它会降低你代码的可读性。
// Longhandlet mychoice: boolean;if (money > 100) {mychoice= true;} else {mychoice= false;}// Shorthandlet mychoice= (money > 10) ? true : false;//or we can use directlylet mychoice= money > 10;console.log(mychoice);
嵌套条件如下所示:
let salary = 300,checking = (salary > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';console.log(checking); // "greater than 100"
3、变量声明
当我们有相同类型的变量时,我们可以避免写入两次。
//Longhandlet data1;let data2= 1;//Shorthandlet data1, data2= 1;
4、检查非空值
如果我们想检查变量不为空怎么办?我们现在可以摆脱再次写入所有条件。
// Longhandif (data1 !== null || data1!== undefined || data1 !== '') {let data2 = data1;}// Shorthandlet data2 = data1 || '';
5、分配默认值
let data1 = null,data2 = test1 || '';console.log("null check", data2); // output will be ""
6、未定义值检查
let data1 = undefined,data2 = data1 || '';console.log("undefined check", data2); // output will be ""
正常值检查
let data1 = 'data',data2 = data1 || '';console.log(data); // output: 'data'
(注意:我们也可以对主题 4,5 和 6使用运算符??)
7、空运算符
如果左侧为空或未定义,则此运算符返回右侧值。
const data= null ?? 'data';console.log(data);// expected output: "data"const data1 = 1 ?? 4;console.log(data1);// expected output: 1
8、赋值
//Longhandlet data1, data2, data3;data1 = 1;data2 = 2;data3 = 3;//Shorthandlet [data1, data2, data3] = [1, 2, 3];
9、赋值运算符
它主要在我们处理算术运算符时使用,就个人而言,我喜欢这里的简写,因为它更具可读性。
// Longhanddata1 = data1 + 1;data2 = data2 - 1;data3 = data3 * 30;// Shorthanddata1++;data2--;data3 *= 30;
10、空检查
最常用的操作数之一,但请确保你的值为真、非空字符串、定义的值和非空值。
// Longhandif (data1 === true) or if (data1 !== "") or if (data1 !== null)// Shorthand //if (test1)
注意:如果 test1 有任何值,它将落入 if 循环之后的逻辑中,该运算符主要用于 null 或 undefined 检查。
11、 AND(&&) 运算符
如果我们想避免少使用一个 if 语句,那么这个技巧会很有帮助。
//Longhandif (test1) {callMethod();}//Shorthandtest1 && callMethod();
12、返回简写
这将有助于避免使用大量代码,专门返回到基于返回语句的调用方法。
// Longhandlet value;function returnMe() {if (!(value === undefined)) {return value;} else {return callFunction('value');}}var data = returnMe();console.log(data); //output valuefunction callFunction(val) {console.log(val);}// Shorthandfunction returnMe() {return value || callFunction('value');}
13、 箭头函数
//Longhandfunction add(a, b) {return a + b;}//Shorthandconst add = (a, b) => a + b;
让我们再看一个例子。
function function(value) {console.log('value', value);}function= value => console.log('value', value);
14、短函数调用
我们可以使用三元运算符来实现这些功能。
// Longhandfunction data1() {console.log('data1');};function data2() {console.log('data2');};var data3 = 1;if (data3 == 1) {data1();} else {data2();} //data1// Shorthand(data3 === 1 ? data1 : data2)(); //data1
15、Switch语句优化
如果你想优化你的 switch 语句,那么这个可以提供帮助。
// Longhandswitch (data) {case 1:data1();break;case 2:data2();break;case 3:data();break;// And so on...}// Shorthandvar data = {1: data1,2: data2,3: data};const val = 1data[val]();function data1() {console.log("data1");}function data2() {console.log("data2");}function data() {console.log("data");}
16、 隐式回报
即使不编写 return 语句,箭头函数也可以帮助返回值,酷吧?
//longhandfunction calculate(diameter) {return Math.PI * diameter}//shorthandcalculate = diameter => (Math.PI * diameter;)
17、十进制指数
// Longhandfor (var i = 0; i < 100000; i++) { ... }// Shorthandfor (var i = 0; i < 1e5; i++) {
18、默认参数值
//Longhandfunction add(data1, data2) {if (data1 === undefined) data1 = 1;if (data2 === undefined) data2 = 2;return data1 + data2;}//shorthandadd = (data1 = 1, data2 = 2) => data1 + data2;console.log(add()); //output: 3
19、 传播运算符
在另一个地方创建数组引用和浅拷贝也很有用。
//longhand// joining arrays using concatconst testdata= [1, 2, 3];const values = [4 ,5 , 6].concat(data);//shorthand// joining arraysconst testdata = [1, 2, 3];const values = [4 ,5 , 6, ...testdata];console.log(test); // [ 4, 5, 6, 1, 2, 3]
对于克隆,我们也可以使用扩展运算符。
//longhand// cloning arraysconst data1 = [1, 2, 3];const data2 = data1.slice()//shorthand// cloning arraysconst data1 = [1, 2, 3];const data2 = [...data1];
20、模板文字
如果你正在寻找以在字符串中附加多个值的技巧的话,那么此技巧适合你。
//longhandconst literal = 'Hi ' + data1 + ' ' + data2 + '.'//shorthandconst literal= `Hi ${data1} ${data2}`;
21、多行字符串
//longhandconst literal = 'abc abc abc abc abc abc\n\t'+ 'val test,test test test test\n\t'//shorthandconst literal = `abc abc abc abc abc abcval test,test test test test`
22、对象属性赋值
let data1 = 'abcd';let data2 = 'efgh';//Longhandlet data = {data1: data1, data2: data2};//Shorthandlet data = {data1, data2};
23、数字转换
//Longhandlet test1 = parseInt('12');let test2 = parseFloat('2.33');//Shorthandlet test1 = +'12';let test2 = +'2.33';
24、解构赋值
//longhandconst data1 = this.data.data1;const data2 = this.data.data2;const data2 = this.data.data3;//shorthandconst { data1, data2, data3 } = this.data;
25、 Array.find 方法
从数组中找到第一个匹配值的方法之一。
const data = [{type: 'data1',name: 'abc'},{type: 'data2',name: 'cde'},{type: 'data1',name: 'fgh'},]function datafinddata(name) {for (let i = 0; i < data.length; ++i) {if (data[i].type === 'data1' && data[i].name === name) {return data[i];}}}//ShorthandfilteredData = data.find(data => data.type === 'data1' && data.name === 'fgh');console.log(filteredData); // { type: 'data1', name: 'fgh' }
26、按位索引
如果我们可以将 indexof 方法与速记结合起来会怎样?按位 indexof 方法为我们做同样的工作。
//longhandif (data.indexOf(item) > -1) { // item found}if (data.indexOf(item) === -1) { // item not found}//shorthandif (~data.indexOf(item)) { // item found}if (!~data.indexOf(item)) { // item not found}
我们也可以使用包含功能。
if (data.includes(item)) {// true if the item found}
27、 Object.entries()
此功能有助于将对象转换为对象数组。
const data = {data1: 'abc',data2: 'cde',data3: 'efg'};const arr = Object.entries(data);console.log(arr);//[['data1', 'abc'],['data2', 'cde'],['data3', 'efg']]
28、Object.values() 和 Object.keys()
迭代对象值会很有帮助。
const data = {data1: 'abc',data2: 'cde'};const arr = Object.values(data);console.log(arr);//[ 'abc', 'cde']
Object.keys() 有助于迭代对象中的键。
const data = {data1: 'abc',data2: 'cde'};const arr = Object.keys(data);console.log(arr);//[ 'data1', 'data2']
29、 双位速记
(双非按位运算符方法仅适用于 32 位整数)
// LonghandMath.floor(1.9) === 1 // true// Shorthand~~1.9 === 1 // true
30、多次重复一个字符串
此字符串方法有助于一次又一次地重复相同的字符串值。
//longhandlet data = '';for (let i = 0; i < 5; i++) {data += 'data ';}console.log(str); // data data data data data//shorthand'data '.repeat(5);
31、查找数组中的最大值和最小值
const data = [1, 4, 3];Math.max(…data); // 4Math.min(…data); // 1
32、从字符串中获取字符
let str = 'test';//Longhandstr.charAt(2); // s//ShorthandNote: this is only works if we know the index of matched characterstr[2]; // c
33、Power 简写
//longhandMath.pow(2,2); // 4//shorthand2**2 // 4
本文完~
学习更多技能
请点击下方公众号
![]()
