<返回更多

23个高级JS编程技巧,你能看懂几个?

2022-09-09  今日头条  WangLiwen
加入收藏

1、console.log输出

console.log(([][[]]+[])[+!![]]+([]+{})[!+[]+!![]])

2、优雅的取随机字符串

Math.random().toString(16).substring(2)

3、if比较

["toString"]() === "10"

4、优雅的取整

var a= 2.33 | 0

5、标准JSON的深拷贝

var a = {
a: 1,
b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))
console.log(b)

6、相等

++[[]][+[]]+[+[]] == 10

7、数组去重

[...new Set([1, "1", 2, 1, 1, 3])]

8、实现一个长度为m(6)且值都n(8)的数组

Array(6).fill(8)

9、取出一个数组中的最大值和最小值

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.Apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
console.log(maxInNumbers,minInNumbers);

10、高逼格的Function

var f = new Function('a', 'alert(a)'); f('jshaman');

Function构造函数接受的参数中,第一个是要传入的参数名,第二个是函数内的代码。

11、判断奇偶数

对一个数字 &1可以判断奇偶数,负数也同样适用, num&1

var num=3;
!!(num & 1) // true
!!(num % 2) // true

12、函数默认值

func = (l, m = 3, n = 4 ) => (l * m * n);
func(2) //output: 24

13、JS代码混淆加密

var a=1;
var b=true;
console.log(a,b);

调用JShaman接口对JS代码进行混淆加密:

14、字符串比较时间先后

var a = "2014-08-08";
var b = "2014-09-09";
console.log(a>b, a<b); // false true

15、使用解构来交换参数数值

有时候你会将函数返回的多个值放在一个数组里。我们可以使用数组解构来获取其中每一个值。

let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1

16、使用解构删除不必要属性

有时候你不希望保留某些对象属性,也许是因为它们包含敏感信息或仅仅是太大了(just too big)。你可能会枚举整个对象然后删除它们,但实际上只需要简单的将这些无用属性赋值给变量,然后把想要保留的有用部分作为剩余参数就可以了。

下面的代码里,我们希望删除_internal和tooBig参数。我们可以把它们赋值给internal和tooBig变量,然后在cleanObject中存储剩下的属性以备后用。

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}

17、在函数参数中解构嵌套对象

在下面的代码中,engine是对象car中嵌套的一个对象。如果我们对engine的vin属性感兴趣,使用解构赋值可以很轻松地得到它。

var car = {
model: 'bmw 2018',
engine: {
v6: true,
turbo: true,
vin: 12345
}
}
const modelAndVIN = ({model, engine: {vin}}) => {
console.log(`model: ${model} vin: ${vin}`);
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345

18、带有多个条件的 if 语句

把多个值放在一个数组中,然后调用数组的 includes 方法。

// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
//logic
}
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) {
//logic
}

19、条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?其实是前面的 switch 简化方式一样!

// bad
if (type === "test1") {
test1();
} else if (type === "test2") {
test2();
} else if (type === "test3") {
test3();
} else if (type === "test4") {
test4();
} else {
throw new Error("Invalid value " + type);
}
// better
var types = {
test1,
test2,
test3,
test4,
};
types[type] && types[type]();

20、跨行字符串

// bad
const data =
"abc abc abc abc abc abcnt" + "test test,test test test testnt";
// better
const data = `abc abc abc abc abc abc
test test,test test test test`;

21、顺序执行 promise

如果你有一堆异步或普通函数都返回 promise,要求你一个接一个地执行,怎么办?

async function getData() {
const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")];
for (const item of promises) {
// 打印出promise
console.log(item);
}
// better
for await (const item of promises) {
// 打印出请求的结果
console.log(item);
}
}

22、打乱数组

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]

23、将Object属性转成属性数组

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: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>