10个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]

2.与或运算

三元运算符是编写简单条件语句的快速方法,如下例子:

x > 100 ? 'above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'above 200' : 'Between 100-200') : 'Below 100';

有时候使用三元运算符处理也会很复杂。我们可以使用与(&&)或(||)运算符来写表达式。这通常被称为‘短路’或‘短路运算’。

它是怎么工作的

使用&&将返回第一个为的值。如果每个操作计算的值都为true,则返回最后一个计算过的表达式。

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0

使用||将返回第一个为的值。如果每个操作数的计算结果都为false,则返回最后一个计算过的表达式。

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null

eg1:

假设我们想返回一个变量的长度,但是我们不知道变量的类型。

我们可以使用if/else语句来检查foo是可接受的类型,但是这可能会变得非常冗长。或运行可以帮助我们简化操作

return (foo || []).length

如果foo是true,它将被返回。否则返回空数组的长度。

eg1:

你是否遇到过访问嵌套对象属性的问题?你可能不知道对象或其中一个子属性是否存在,这可能会导致令人沮丧的错误。

假设我们想在this.state中访问一个名为data的属性,但是在我们的程序成功返回一个获取请求之前,data 是未定义的。

根据我们使用它的位置,调用this.state.data可能会阻止我们的应用程序运行。为了解决这个问题,我们可以将其做进一步的判断:

if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}

但这似乎很重复。'或' 运算符提供了更简洁的解决方案:

return (this.state.date || 'Fetching Data');

3.转化为布尔值

除了另有定义,否则JavaScript中所有的值都是真值,假值有0,"", null, undefined, NaN,false。

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

4.转化为字符串

要快速地将数字转换为字符串,我们可以使用连接运算符+后跟一组空引号""

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

5.转化为数字

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

6.性能更好的运算

从ES7开始,可以使用指数运算符**作为幂的简写,这比编写Math.pow(2, 3) 更快。这是很简单的东西,但它之所以出现在列表中,是因为没有多少教程更新过这个操作符。

console.log(2 ** 3); // Result: 8

7.快速浮点数转整数

如果希望将浮点数转换为整数,可以使用Math.floor()Math.ceil()Math.round()。但是还有一种更快的方法可以使用|(位或运算符)将浮点数截断为整数。

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

8.数组截断

如果要从数组的末尾删除值,有比使用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]

9.获取数组中的最后一项

数组方法slice()可以接受负整数,如果提供它,它将接受数组末尾的值,而不是数组开头的值。

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]

10.获取数组中的最后一项

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

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

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

猜你喜欢

转载自www.cnblogs.com/wangtao-/p/11912280.html