ES6

149 阅读5分钟

1、模板字符串

1. 模板字符串

需要拼接字符串的时候尽量改成使用模板字符串:

// 例子 2-1

![213246-1586525566e909.jpg](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/392671b93528464696a0b78b9d59efaf~tplv-k3u1fbpfcp-watermark.image)
// bad
const foo = 'this is a' + example;

// good
const foo = `this is a ${example}`;

2. 标签模板

可以借助标签模板优化书写方式:

// 例子 2-2

let url = `
    www.taobao.com/example/index.html
    ?foo=${foo}
    &bar=${bar}
`;

console.log(url); // www.taobao.com/example/index.html?foo=foo&bar=bar

2、Set 和 Map

1. 数组去重

// 例子 5-1

[...new Set(array)]

2. 条件语句的优化

// 例子 5-2
// 根据颜色找出对应的水果

// bad
function test(color) {
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

test('yellow'); // ['banana', 'pineapple']
// good
const fruitColor = {
  red: ['apple', 'strawberry'],
  yellow: ['banana', 'pineapple'],
  purple: ['grape', 'plum']
};

function test(color) {
  return fruitColor[color] || [];
}
// better
const fruitColor = new Map()
  .set('red', ['apple', 'strawberry'])
  .set('yellow', ['banana', 'pineapple'])
  .set('purple', ['grape', 'plum']);

function test(color) {
  return fruitColor.get(color) || [];
}

3、for of

1. 遍历范围

for...of 循环可以使用的范围包括:

  • 数组
  • Set
  • Map
  • 类数组对象,如 arguments 对象、DOM NodeList 对象
  • Generator 对象
  • 字符串

2.优势

ES2015 引入了 for..of 循环,它结合了 forEach 的简洁性和中断循环的能力:

// 例子 6-1

for (const v of ['a', 'b', 'c']) {
  console.log(v);
}
// a b c

for (const [i, v] of ['a', 'b', 'c'].entries()) {
  console.log(i, v);
}
// 0 "a"
// 1 "b"
// 2 "c"

3.遍历 Map

// 例子 6-2

let map = new Map(arr);

// 遍历 key 值
for (let key of map.keys()) {
  console.log(key);
}

// 遍历 value 值
for (let value of map.values()) {
  console.log(value);
}

// 遍历 key 和 value 值(一)
for (let item of map.entries()) {
  console.log(item[0], item[1]);
}

// 遍历 key 和 value 值(二)
for (let [key, value] of data) {
  console.log(key)
}

4.Promise

1.基本示例

// 例子 7-1

// bad
request(url, function(err, res, body) {
    if (err) handleError(err);
    fs.writeFile('1.txt', body, function(err) {
        request(url2, function(err, res, body) {
            if (err) handleError(err)
        })
    })
});

// good
request(url)
.then(function(result) {
    return writeFileAsynv('1.txt', result)
})
.then(function(result) {
    return request(url2)
})
.catch(function(e){
    handleError(e)
});

2.finally

// 例子 7-2

fetch('file.json')
.then(data => data.json())
.catch(error => console.error(error))
.finally(() => console.log('finished'));

5.Async

1.代码更加简洁

// 例子 8-1

// good
function fetch() {
  return (
    fetchData()
    .then(() => {
      return "done"
    });
  )
}

// better
async function fetch() {
  await fetchData()
  return "done"
};


// 例子 8-2

// good
function fetch() {
  return fetchData()
  .then(data => {
    if (data.moreData) {
        return fetchAnotherData(data)
        .then(moreData => {
          return moreData
        })
    } else {
      return data
    }
  });
}

// better
async function fetch() {
  const data = await fetchData()
  if (data.moreData) {
    const moreData = await fetchAnotherData(data);
    return moreData
  } else {
    return data
  }
};


// 例子 8-3

// good
function fetch() {
  return (
    fetchData()
    .then(value1 => {
      return fetchMoreData(value1)
    })
    .then(value2 => {
      return fetchMoreData2(value2)
    })
  )
}

// better
async function fetch() {
  const value1 = await fetchData()
  const value2 = await fetchMoreData(value1)
  return fetchMoreData2(value2)
};

2.错误处理

// 例子 8-4

// good
function fetch() {
  try {
    fetchData()
      .then(result => {
        const data = JSON.parse(result)
      })
      .catch((err) => {
        console.log(err)
      })
  } catch (err) {
    console.log(err)
  }
}

// better
async function fetch() {
  try {
    const data = JSON.parse(await fetchData())
  } catch (err) {
    console.log(err)
  }
};

3."async 地狱"

// 例子 8-5

// bad
(async () => {
  const getList = await getList();
  const getAnotherList = await getAnotherList();
})();

// good
(async () => {
  const listPromise = getList();
  const anotherListPromise = getAnotherList();
  await listPromise;
  await anotherListPromise;
})();

// good
(async () => {
  Promise.all([getList(), getAnotherList()]).then(...);
})();

6.class

构造函数尽可能使用 Class 的形式

// 例子 9-1

class Foo {
  static bar () {
    this.baz();
  }
  static baz () {
    console.log('hello');
  }
  baz () {
    console.log('world');
  }
}

Foo.bar(); // hello


// 例子 9-2

class Shape {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }
  get area() {
    return this._width * this._height;
  }
}

const square = new Shape(10, 10);
console.log(square.area);    // 100
console.log(square._width);  // 10

7.函数

1.默认值

// 例子 11-1

// bad
function test(quantity) {
  const q = quantity || 1;
}

// good
function test(quantity = 1) {
  ...
}



// 例子 11-2

doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });

// bad
function doSomething(config) {
  const foo = config.foo !== undefined ? config.foo : 'Hi';
  const bar = config.bar !== undefined ? config.bar : 'Yo!';
  const baz = config.baz !== undefined ? config.baz : 13;
}

// good
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
  ...
}

// better
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
  ...
}


// 例子 11-3

// bad
const Button = ({className}) => {
	const classname = className || 'default-size';
	return <span className={classname}></span>
};

// good
const Button = ({className = 'default-size'}) => (
	<span className={classname}></span>
);

// better
const Button = ({className}) =>
	<span className={className}></span>
}

Button.defaultProps = {
	className: 'default-size'
}


// 例子 11-4

const required = () => {throw new Error('Missing parameter')};

const add = (a = required(), b = required()) => a + b;

add(1, 2) // 3
add(1); // Error: Missing parameter.

8.拓展运算符

1.arguments 转数组

// 例子 12-1

// bad
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// good
const sortNumbers = (...numbers) => numbers.sort();

2.调用参数

// 例子 12-2

// bad
Math.max.apply(null, [14, 3, 77])

// good
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);

3.构建对象

剔除部分属性,将剩下的属性构建一个新的对象

// 例子 12-3
let [a, b, ...arr] = [1, 2, 3, 4, 5];

const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };

有条件的构建对象

// 例子 12-4

// bad
function pick(data) {
  const { id, name, age} = data

  const res = { guid: id }

  if (name) {
    res.name = name
  }
  else if (age) {
    res.age = age
  }

  return res
}

// good
function pick({id, name, age}) {
  return {
    guid: id,
    ...(name && {name}),
    ...(age && {age})
  }
}

合并对象

// 例子 12-5

let obj1 = { a: 1, b: 2,c: 3 }
let obj2 = { b: 4, c: 5, d: 6}
let merged = {...obj1, ...obj2};

9.解构赋值

1.对象的基本结构

// 例子 14-1

componentWillReceiveProps(newProps) {
	this.setState({
		active: newProps.active
	})
}

componentWillReceiveProps({active}) {
	this.setState({active})
}


// 例子 14-2

// bad
handleEvent = () => {
  this.setState({
    data: this.state.data.set("key", "value")
  })
};

// good
handleEvent = () => {
  this.setState(({data}) => ({
    data: data.set("key", "value")
  }))
};


// 例子 14-3

Promise.all([Promise.resolve(1), Promise.resolve(2)])
.then(([x, y]) => {
    console.log(x, y);
});

2.对象深度解构

// 例子 14-4

// bad
function test(fruit) {
  if (fruit && fruit.name)  {
    console.log (fruit.name);
  } else {
    console.log('unknown');
  }
}

// good
function test({name} = {}) {
  console.log (name || 'unknown');
}


// 例子 14-5

let obj = {
    a: {
      b: {
        c: 1
      }
    }
};

const {a: {b: {c = ''} = ''} = ''} = obj;

3.数组解构

// 例子 14-6

// bad
const spliteLocale = locale.splite("-");
const language = spliteLocale[0];
const country = spliteLocale[1];

// good
const [language, country] = locale.splite('-');

4.变量重命名

// 例子 14-8

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
console.log(baz); // "aaa"

5.仅获取部分属性

// 例子 14-9

function test(input) {
  return [left, right, top, bottom];
}
const [left, __, top] = test(input);

function test(input) {
  return { left, right, top, bottom };
}
const { left, right } = test(input);

10.增强的对象字面量

// 例子 15-1

// bad
const something = 'y'
const x = {
  something: something
}

// good
const something = 'y'
const x = {
  something
};

动态属性

// 例子 15-2

const x = {
  ['a' + '_' + 'b']: 'z'
}

console.log(x.a_b); // z

11.数组的拓展方法

1.keys

// 例子 16-1

var arr = ["a", , "c"];

var sparseKeys = Object.keys(arr);
console.log(sparseKeys); // ['0', '2']

var denseKeys = [...arr.keys()];
console.log(denseKeys);  // [0, 1, 2]

2.entries

// 例子 16-2

var arr = ["a", "b", "c"];
var iterator = arr.entries();

for (let e of iterator) {
    console.log(e);
}

3.values

// 例子 16-3

let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();

for (let letter of eArr) {
  console.log(letter);
}

4.includes

// 例子 16-4

// bad
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }
}

// good
function test(fruit) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}

5.find

// 例子 16-5

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

6.findIndex

// 例子 16-6

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2