一些js精简的技巧

1、过滤唯一值:

const arr = [1, 1, 2, 3, 5, 5, 1]
const uniqueArr = [...new Set(arr)]
console.log(uniqueArr) // [1,2,3,5]

  其中的Set为es6新增属性

2、与或运算:

其实与或运算的精简之处就可以使用三目运算来表示

x > 100 ? '>100' : '<100'

x > 100 ? (x > 200 ? '>200' : '100-200') : '<100'

  

当然有的使用三目运算写起来更加的麻烦,所以还是需要具体情况具体分析。

let one = 1, two = 2, three = 3

console.log(one && two && three); // 3

console.log(0 && null); // 0

  这是使用了&&运算。

let one = 1, two = 2, three = 3

console.log(one || two || three); // 1

console.log(0 || null); // null

  这是使用了||运算

3、转换为布尔值

const isTrue  = !0

const isFalse = !1

const alsoFalse = !!0

console.log(isTrue) // true

console.log(typeof true) // boolean

  

4、转换为字符串

const val = 1 + ""

console.log(val) //  "1“

console.log(typeof val) // string

  

5、转换为数字

let int = "15"

int = +int

console.log(int) // 15

console.log(typeof int) // number

  

6、性能更好的运算

计算幂次方:

console.log(2 ** 3) // 8    表示2的3次方

  

7、快速浮点数转整数

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

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

  

删除最后一位数字:

let str = "1553"

Number(str.substring(0, str.length - 1))  // 155

  

可以简写为:

console.log(1553 / 10   | 0)  //  155

console.log(1553 / 100  | 0)  // 15

console.log(1553 / 1000 | 0)  //  1

  

8、类中的自动绑定

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>
      </>
    )
  }
};

  

9、数组截断

a、如果你知道原始数组的大小,您可以重新定义它的length属性,如

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

array.length = 4

console.log(array) // [0, 1, 2, 3]

  

b、slice()方法的运行时更快

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

array = array.slice(0, 4)

console.log(array) // [0, 1, 2, 3]

  

10、获取数组中的最后项

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(array.slice(-1)) //  [9]

console.log(array.slice(-2)) //  [8, 9]

console.log(array.slice(-3)) //  [7, 8, 9]

  

11、格式化JSON代码

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

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

posted @ 2020-01-10 14:52  zaijinyang  阅读(401)  评论(0编辑  收藏  举报