几个经常用到的js小技巧

1、过滤唯一值

Set对象类型是在ES6中引入的,配合展开操作...一起,我们可以使用它来创建一个新数组,该数组只有唯一的值。

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

在ES6之前,隔离唯一值将涉及比这多得多的代码。

此技巧适用于包含基本类型的数组:undefined,null,boolean,string和number。(如果你有一个包含对象,函数或其他数组的数组,你需要一个不同的方法!)

2、转换为布尔值

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

 3、 转换为字符串

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

 4、转换为数字

使用加法运算符+可以快速实现相反的效果。

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

这也可以用于将布尔值转换为数字,如下所示

console.log(+true);  // Return: 1
 console.log(+false); // Return: 0

5、数组截断

如果要从数组的末尾删除值,有比使用splice()更快的方法。

例如,如果你知道原始数组的大小,您可以重新定义它的length属性,就像这样

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

 这是一个特别简洁的解决方案。但是,我发现slice()方法的运行时更快。如果速度是你的主要目标,考虑使用:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]

6、 获取数组中的最后一项

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

7、格式化JSON代码

最后,你之前可能已经使用过JSON.stringify,但是您是否意识到它还可以帮助你缩进JSON?

stringify()方法有两个可选参数:一个replacer函数,可用于过滤显示的JSON和一个空格值

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

猜你喜欢

转载自blog.csdn.net/AN0692/article/details/105806460
今日推荐