ES6 中可以提升幸福度的小功能中可以提升幸福度的小功能
主要介绍了ES6 中可以提升幸福度的小功能,在量解构赋值的用途,函数的用处等方面给大家介绍,需要的朋友
可以参考下
一、变量解构赋值的用途一、变量解构赋值的用途
1)交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x]
2)从函数返回多个值
// 返回一个数组
function example(){
return [1, 2, 4];
}
let [a, b, c] = example()
// 返回一个对象
function example(){
return {
foo:1,
bar: 2
}
}
let {foo, bar} = example(); 或者 ( {foo, bar} = example() )
3)提取JSON数据
let jsonData = {
id:42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number} = jsonData;
4)输入模块的指定方法
加载模块时,往往需要指定输入的方法,解构赋值使得输入语句非常清晰
const { SourceMapConsumer, SourceNode } = require("source-map")
5) 数组复制的功能
在es5中,开发者经常使用 concat() 方法克隆数组:
// 在 es5 中克隆数组
var colors = [ 'red', 'green', 'blue' ];
var clonedColors = colors.concat();
console.log(clonedColors); // "[red, green, blue]"
concat() 方法的设计初衷是连接两个数组,如果调用时不传递参数就会返回当前数组的副本。在es6中可以通过不定元素的语
法来实现相同的目标:
let colors = [ 'red', 'green', 'blue' ]
let [ ...clonedColors ] = colors;
console.log(clonedColors); // "[red, green, blue]"
6) 结合Set集合,创建一个无重复元素的数组
function eliminateDuplicates(items) {
return [...new Set(items)]
}
let numbers = [1, 2, 3, 3, 3, 4, 5];
let noDuplicates = eliminateDuplicates(numbers );
console.log(noDuplicates ); // [1,2,3,4,5]
7) 使用apply 把两个数据合并成一个
var arra1 = [{
name: '小智',
age: 26
}]
var arra2 = [{
name: '大智',