ES6 小技巧

 

1. 强制要求参数

ES6提供了默认参数值机制,允许你为参数设置默认值,防止在函数被调用时没有传入这些参数。在下面的例子中,我们写了一个 required()函数作为参数a和b的默认值。这意味着如果a或b其中有一个参数没有在调用时传值,会默认 required()函数,然后抛出错误。

	const required = () => {thrownewError('Missing parameter')};
	const add = (a = required(), b = required()) => a + b;	
	add(1, 2) //3
	add(1) // Error: Missing parameter.

2. 强大的reduce

  使用reduce同时实现map和filter

假设现在有一个数列,你希望更新它的每一项(map的功能)然后筛选出一部分(filter的功能)。如果是先使用map然后filter的话,你需要遍历这个数组两次。

在下面的代码中,我们将数列中的值翻倍,然后挑选出那些大于50的数。

const numbers = [10, 20, 30, 40];
const doubledOver50 = 
   numbers.reduce((finalList, num) => {
       num = num * 2; 
 if (num > 50) {
    finalList.push(num);
	  }
	  return finalList;
	}, 
[]);
	doubledOver50; // [60, 80]

 使用reduce匹配圆括号

reduce的另外一个用途是能够匹配给定字符串中的圆括号。对于一个含有圆括号的字符串,我们需要知道 "("和 ")"的数量是否一致,并且 "("是否出现在 ")"之前。

下面的代码中我们使用reduce可以轻松地解决这个问题。我们只需要先声明一个 counter变量,初值为0。在遇到 "("时counter加一,遇到 ")"时counter减一。如果左右括号数目匹配,那最终结果为0。

//Returns 0 if balanced.
	const isParensBalanced = (str) => {
	  return str.split('').reduce((counter, char) => {
	    if(counter < 0) { //matched ")" before "("
	      return counter;
    } else if(char === '(') {
	      return ++counter;
	    } else if(char === ')') {
     return --counter;
	    }  else { //matched some other char
      return counter;
    }

  }, 0); //<-- starting value of the counter
	}
	isParensBalanced('(())') // 0 <-- balanced
	isParensBalanced('(asdfds)') //0 <-- balanced
	isParensBalanced('(()') // 1 <-- not balanced
	isParensBalanced(')(') // -1 <-- not balanced

统计数组中相同项的个数

很多时候,你希望统计数组中重复出现项的个数然后用一个对象表示。那么你可以使用reduce方法处理这个数组。

下面的代码将统计每一种车的数目然后把总数用一个对象表示。

	var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
	var carsObj = cars.reduce(function (obj, name) { 
	   obj[name] = obj[name] ? ++obj[name] : 1;
	  return obj;
	}, {});
	carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }

3. 对象解构

 删除不需要的属性

下面的代码里,我们希望删除 _internaltooBig参数。我们可以把它们赋值给 internaltooBig变量,然后在 cleanObject中存储剩下的属性以备后用。

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
  console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}

在函数参数中解构嵌套对象

在下面的代码中, engine是对象 car中嵌套的一个对象。如果我们对 enginevin属性感兴趣,使用解构赋值可以很轻松地得到它。

	var car = {
	  model: 'bmw 2018',
    engine: {
	    v6: true,
	    turbo: true,
	    vin: 12345
	  }
	}
	const modelAndVIN = ({model, engine: {vin}}) => {
	  console.log(`model: ${model} vin: ${vin}`);
	}
	modelAndVIN(car); // => model: bmw 2018  vin: 12345

合并对象

ES6带来了扩展运算符(...)。它一般被用来解构数组,但你也可以用它处理对象。

接下来,我们使用扩展运算符来展开一个新的对象,第二个对象中的属性值会改写第一个对象的属性值。比如 object2bc就会改写 object1的同名属性。

	let object1 = { a:1, b:2,c:3 }
	let object2 = { b:30, c:40, d:50}
	let merged = {…object1, …object2} //spread and re-add into merged
	console.log(merged) // {a:1, b:30, c:40, d:50}

Sets

使用Set实现数组去重

在ES6中,因为Set只存储唯一值,所以你可以使用Set删除重复项。

	let arr = [1, 1, 2, 2, 3, 3];
	let deduped = [...newSet(arr)] // [1, 2, 3]

对Set使用数组方法

使用扩展运算符就可以简单的将Set转换为数组。所以你可以对Set使用Array的所有原生方法。比如我们想要对下面的Set进行filter操作,获取大于3的项。

	let mySet = newSet([1,2, 3, 4, 5]);
	var filtered = [...mySet].filter((x) => x >3) // [4, 5]

4.数组解构

有时候你会将函数返回的多个值放在一个数组里。我们可以使用数组解构来获取其中每一个值。

数值交换

	let param1 = 1;
	let param2 = 2;
	//swap and assign param1 & param2 each others values
	[param1, param2] = [param2, param1];
	console.log(param1) // 2
	console.log(param2) // 1

接收函数返回的多个结果

在下面的代码中,我们从 /post中获取一个帖子,然后在 /comments中获取相关评论。由于我们使用的是 async/await,函数把返回值放在一个数组中。而我们使用数组解构后就可以把返回值直接赋给相应的变量。

	async function getFullPost(){
	  return await Promise.all([
	    fetch('/post'),
	    fetch('/comments')
	  ]);
	}
	const [post, comments] = getFullPost();

5.设置对象变量键值的语法

以前不能在对象字面量里设置变量键值——必须要在初始化后对象后增加变量键/值:

let myKey = 'key3';

let obj = {

    key1: 'One',

    key2: 'Two'

};

obj[myKey] = 'Three';

ES6提供了一个解决方法:

let myKey = 'variableKey';

let obj = {

    key1: 'One',

    key2: 'Two',

    [myKey]: 'Three' /* yay! */

};

6.find/findIndex

JavaScript提供了 Array.prototype.indexOf方法,用来获取一个元素在数组中的索引,但是 indexOf方法不能计算目标元素的查找条件。有时候你还会想获取满足查找条件的那个元素本身。输入 find和 findIndex吧——这两个方法可以在一个数组搜索出第一个满足条件的值。

let ages = [12, 19, 6, 4];


let firstAdult = ages.find(age => age >= 18); // 19

let firstAdultIndex = ages.findIndex(age => age >= 18); // 1

猜你喜欢

转载自blog.csdn.net/cao_dan/article/details/81742426