12 个 JS 技巧

1. 过滤惟一值

ES6 引入了 Set 对象和延展(spread)语法…,咱们能够用它们来建立一个只包含惟一值的数组。算法

复制代码
 
 
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. 在循环中缓存数组长度

在咱们学习使用 for 循环时,通常建议使用这种结构:函数

复制代码
 
 
for (let i = 0; i < array.length; i++){
 
  console. log(i);
 
}

在使用这种方式时,for 循环的每次迭代都会重复计算数组长度。性能

有时候这个会颇有用,但在大多数状况下,若是可以缓存数组的长度会更好,这样只须要计算一次就够了。咱们能够把数组长度复制给一个叫做 length 的变量,例如:学习

复制代码
 
 
for (let i = 0, length = array.length; i < length; i++){
 
  console. log(i);
 
}

这段代码和上面的差很少,但从性能方面来看,即便数组变得很大,也不须要花费额外的运行时重复计算 array.length。ui

3. 短路求值

使用三元运算符能够很快地写出条件语句,例如:this

复制代码
 
 
x > 100 ? 'Above 100' : 'Below 100';
 
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

但有时候三元运算符仍然很复杂,咱们可使用逻辑运算符 && 和||来替代,让代码更简洁一些。这种技巧一般被称为“短路求值”。spa

假设咱们想要返回两个或多个选项中的一个,使用 && 能够返回第一个 false。若是全部操做数的值都是 true,将返回最后一个表达式的值。code

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

使用||能够返回第一个 true。若是全部操做数的值都是 false,将返回最后一个表达式的值。

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

示例 1

假设咱们想要返回一个变量的 length,但又不知道变量的类型。

咱们可使用 if/else 来检查 foo 是不是一个可接受的类型,但这样会让代码变得很长。这个时候可使用短路求值:

复制代码
 
 
return (foo || []).length;

对于上述两种状况,若是变量 foo 具备 length 属性,这个属性的值将被返回,不然将返回 0。

示例 2

你是否曾经在访问嵌套对象属性时遇到过问题?你可能不知道对象或某个子属性是否存在,因此常常会碰到让你头疼的错误。

假设咱们想要访问 this.state 中的一个叫做 data 的属性,但 data 倒是 undefined 的。在某些状况下调用 this.state.data 会致使 App 没法运行。为了解决这个问题,咱们可使用条件语句:

复制代码
 
 
if (this.state.data) {
 
  return this.state.data;
 
} else {
 
  return 'Fetching Data';
 
}

但这样彷佛有点啰嗦,而||提供了更简洁的解决方案:

复制代码
 
 
return (this.state.data || 'Fetching Data');

4. 转换成布尔值

除了标准的布尔值 true 和 false,在 JavaScript 中,全部的值要么是“真值”要么是“假值”。

在 JavaScript 中,除了 0、“”、null、undefined、NaN 和 false 是假值以外,其余的都是真值。

咱们可使用! 云算法来切换 true 和 false。

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

5. 转换成字符串

要快速将数字转换成字符串,咱们可使用 + 运算符,而后在后面跟上一个空字符串。

复制代码
 
 
const val = 1 + "";
 
console.log(val); // Result: "1"
 
console.log(typeof val); // Result: "string"

6. 转换成数字

要把字符串转成数字,也可使用 + 运算符。

复制代码
 
 
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

在某些状况下,+ 运算符会被解析成链接操做,而不是加法操做。对于这种状况,可使用两个波浪号:~~。

一个波浪号表示按位取反操做,例如,~15 等于 -16。

复制代码
 
 
const int = ~~"15"
 
console.log(int); // Result: 15
 
console.log(typeof int); Result: "number"

使用两个波浪号能够再次取反,由于 -(-n-1)=n+1-1=n,因此~-16 等于 15。

7. 快速幂运算

从 ES7 开始,可使用 ** 进行幂运算,比使用 Math.power(2,3) 要快得多。

复制代码
 
 
console.log( 2 ** 3); // Result: 8

但要注意不要把这个运算符于 ^ 混淆在一块儿了,^ 一般用来表示指数运算,但在 JavaScript 中,^ 表示位异或运算。

在 ES7 以前,可使用位左移运算符 << 来表示以 2 为底的幂运算:

复制代码
 
 
// 如下表达式是等效的:
 
Math.pow( 2, n);
 
2 << (n - 1);
 
2**n;

例如,2 << 3 = 16 等同于 2 ** 4 = 16。

8. 快速取整

咱们可使用 Math.floor()、Math.ceil() 或 Math.round() 将浮点数转换成整数,但有另外一种更快的方式,即便用位或运算符 |。

复制代码
 
 
console.log( 23.9 | 0);  // Result: 23
 
console.log( -23.9 | 0); // Result: -23

| 的实际行为取决于操做数是正数仍是负数,因此在使用这个运算符时要确保你知道操做数是正是负。

若是 n 是正数,那么 n|0 向下取整,不然就是向上取整。它会移除小数部分,也可使用~~ 达到一样的效果。

移除整数尾部数字

| 运算符也能够用来移除整数的尾部数字,这样就不须要像下面这样:

复制代码
 
 
let str = "1553"; 
 
Number(str.substring(0, str.length - 1));

相反,咱们能够这样:

复制代码
 
 
console.log( 1553 / 10   | 0)  // Result: 155
 
console.log( 1553 / 100  | 0)  // Result: 15
 
console.log( 1553 / 1000 | 0)  // Result: 1

9. 自动类绑定

在 ES6 中,咱们可使用箭头进行隐式绑定,这样能够为类的构造器省下一些代码,并跟一些重复出现的表达式说再见,好比 this.myMethod = this.myMethod.bind(this)。

复制代码
 
 
import React, { Component } from React;
 
export default class App extends Compononent {
 
  constructor(props) {
 
  super(props);
 
  this.state = {};
 
  }
 
myMethod = () => {
 
    // This method is bound implicitly!
 
  }
 
render() {
 
    return (
 
      <>
 
        <div>
 
          {this.myMethod()}
 
        </div>
 
      </>
 
    )
 
  }
 
};
   

10. 截取数组

若是你想从一个数组尾部移除某些元素,可使用一种比 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]

11. 获取数组最后的元素

数组的 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]

12. 格式化 JSON

你以前可能使用过 JSON.stringify,但你是否知道它还能够用来给 JSON 添加缩进?

stringify() 方法能够接受两个额外的参数,一个是函数(形参为 replacer),用于过滤要显示的 JSON,另外一个是空格个数(形参为 space)。

space 能够是一个整数,表示空格的个数,也能够是一个字符串(好比’\t’表示制表符),这样获得的 JSON 更容易阅读。

复制代码
 
 
console. log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
 
// Result:
 
// '{
 
//     "alpha": A,
 
//     "beta": B
 
// }'
相关文章
相关标签/搜索