JS简写小技巧,助你高效敲代码
· 预计阅读时间:3 分钟
Tags:js
note
本文更新一些js可以常用的简写小技巧,持续更新
#
1.同时声明多个变量let x;let y = 20;
let x, y = 20;
#
2.多变量赋值
let a, b, c;a = 5;b = 8;c = 12;
let [a, b, c] = [5, 8, 12];
#
3、简化分支条件语句let nmb = 26;let result;if(nmb >= 30){ result = '大于等于30';}else{ result = '小于30';}
let result = nmb >= 30 ? ''大于等于30'' : '小于30';
#
4、判断变量是否存if (test1 === true) or if (test1 !== "") or if (test1 !== null)
if (test1)
#
5、与 (&&) 短路运算if (isLoggedin) { goToHomepage();}
isLoggedin && goToHomepage();
#
6、交换两个变量let x = 'Hello', y = 55;
const temp = x;x = y;y = temp;
//简写使用解构赋值[x, y] = [y, x];
#
7、箭头函数
function add(num1, num2) { return num1 + num2;}
const add = (num1, num2) => num1 + num2;
#
8、赋值运算符test1 = test1 + 1;test2 = test2 - 1;test2 = test2 - 10;test2 = test2 + 10;test3 = test3 * 20;
test1++;test2--;test3 += 10;test3 -= 10;test3 *= 20;
#
9、数组合并const data = [1, 2, 3];const test = [4 ,5 , 6].concat(data);
const data = [1, 2, 3];const test = [4 ,5 , 6, ...data];console.log(test); // [ 4, 5, 6, 1, 2, 3]
#
10、对象数组中按属性值查找对象const data = [{ type: 'test1', name: 'abc' }, { type: 'test2', name: 'cde' }, { type: 'test1', name: 'fgh' },]function findtest1(name) { for (let i = 0; i < data.length; ++i) { if (data[i].type === 'test1' && data[i].name === name) { return data[i]; } }}
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');console.log(filteredData); // { type: 'test1', name: 'fgh' }
#
11、字符串转成数字
let total = parseInt('168');let average = parseFloat('52.8');
let total = +'168';let average = +'52.8';
let total = '168'-0;let average = +'52.8'-0;
#
12、重复字符串多次let str = '';for(let i = 0; i < 5; i ++) { str += 'Hello ';}console.log(str); // Hello Hello Hello Hello Hello
'Hello '.repeat(5);
#
13、获取字符串中某个字符let str = 'abc';
str.charAt(2);
str[2]; //注意:如果事先知道目标字符在字符串中的索引,我们可以直接使用该索引值。如果索引值不确定,运行时就有可能抛出 undefined。
#
14、多条件检查
if (value === 1 || value === '吃的' || value === "玩" || value === '喝的') { }
if ([1, '吃的',"玩", '喝的'].indexOf(value) >= 0) { }
if ([1, '吃的', "玩", '喝的'].includes(value)) {
}
#
15、数组中的最大和最小数字const arr = [12, 8, 150, 24];Math.max(...arr); // 150Math.min(...arr); // 8