1.if多重条件判断
通常多个条件只有一个满足,我们一般使用|| 或运算符 ==es6以后可以使用Array.includes
let x = "aaa";
if (["aaa", "bbb", "ccc", "jkl"].includes(x)) {
console.log(x);
}
2.if…else的缩写写法
if-else 简单可以用三元表达式
3.同时为多个变量赋值
不同变量赋值 +es6的解构赋值
let [test1, test2, test3] = [1, 2, 3];
console.log(test1, test2);
4.多条件的&& (与)运算符
let test1 = 1 == 2;
let test2 = 2 == 2;
console.log(test1 || test2);
5.比较结果的返回
在return 语句中,我们也可以使用||或运算符
let test;
function fn2() {
console.log(111);
}
function fn() {
if (!(test === undefined)) {
return test;
} else {
return fn2();
}
}
fn();
6.Switch对应的缩写法
function test1() {
console.log("11");
}
function test2() {
console.log("22");
}
function test3() {
console.log("33");
}
var n = 1;
var data = {
1: test1,
2: test2,
3: test3,
};
data[n] && data[n]();
7.重复字符串
var str = "test ".repeat(5);
console.log(str);
8.找出一个数组最大值和最小值
var arr = [1, 5, 941, 152, 1, 6, 4, 8];
var max = arr[0];
var min = arr[0];
for (let i = 0; i < arr.length; i++) {
max = max > arr[i] ? max : arr[i];
min = min < arr[i] ? min : arr[i];
}
console.log(max, min);
var arr = [1, 5, 941, 152, 1, 6, 4, 8];
var max = Math.max(...arr);
var min = Math.min(...arr);
console.log(max, min);
9.数组去重
普通写法
var arr = [1, 5, 941, 152, 1, 6, 4, 8, 1, 56, 3, 4];
var arr2 = [...new Set(arr)];
console.log(arr2);
10.查询条件缩写法
var type = "test1";
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4,
};
var func = types[type];
func ? func() : test();
11.indexOf缩写
arr = [1, 45, 4, 51];
if (~arr.indexOf(1)) {
console.log(111);
}
if (!~arr.indexOf(2)) {
console.log(222);
}
12.??空值合并操作符
const data = "111";
const value = data ?? "000";
console.log(value);
13.链判断符进行非空判断
const value = reponse?.data?.text;
console.log(value);
14.获取数组的最后一项
let arr = [1, 2156, 4, 5, 5];
console.log(arr[arr.length - 1]);
console.log(arr.at(-1));
15.字符串值转成数组
let str = "123";
console.log(parseInt(str));
let str ="123"
console.log(+str);
16.变量值不存在赋值
let foo = null;
foo = foo || 111;
console.log(foo);
17.去除数组空项
let arr = [1, 2, , 3, 4, 5];
console.log(arr.flat());
console.log(arr);