ES6+好用的小技巧,让你的代码更干净,短巧,易读

栏目: JavaScript · 发布时间: 6年前

ES6+好用的小技巧,让你的代码更干净,短巧,易读

模板字符串

let name = 'siri', age = 18, job = 'front-end engineer'
let oldStr = 'Hi, ' + name + ', I\'m ' + age + ' and work as a ' + job + '.';

let newStr = `Hi, ${ name }, I'm ${ age } and work as a ${ job }.`;

扩展操作符

… 操作符,有两个主要用处:

  1. 复制一个新的数组或对象
  2. 把多个参数赋值给一个数组变量
  3. 把一个数组变量赋值给多个参数
let a = [1, 2, 3]
let b = [...a] // b是一个新的数组,内容和a一样
let c = [...a, 4, 5, 6]

let car = { type: 'vehicle ', wheels: 4};
let newCar = {...car}
console.log(newCar); // { type: 'vehicle ', wheels: 4}

// 合并对象属性,后边的属性会覆盖前边的,可用于修改对象的某个属性值
let car2 = {...car, type: 'vehicle2', wheels: 2} // {type: "vehicle2", wheels: 2}
function foo(...args) {
    console.log(args); 
} 
foo( 'car', 54, 'tree');  //  console.log 输出 [ 'car', 54, 'tree' ]

默认参数

// 给方法添加默认参数值
function foo( a = 5, b = 10) {
    console.log( a + b);
} 
foo();  // 15
foo( 7, 12 );  // 19
foo( undefined, 8 ); // 13
foo( 8 ); // 18
foo( null ); // 10 as null is coerced to 0
// 默认参数值也可以是表达式或者函数
function foo( a ) { return a * 4; }

// y = x + 4, z = foo(x)
function bar( x = 2, y = x + 4, z = foo(x)) {
    console.log([ x, y, z ]);
}

bar();  // [ 2, 6, 8 ]
bar( 1, 2, 3 ); //[ 1, 2, 3 ] 
bar( 10, undefined, 3 );  // [ 10, 14, 3 ]
// 对象参数默认值,如果参数为空,则会抛出异常
function show({ title = "title", width = 100, height = 200 }) {
  console.log( `${title} ${width} ${height}` );
}
show() // Cannot destructure property `title` of 'undefined' or 'null'.
show({}) // title 100 200

// 解决办法:
function show({ title = "title", width = 100, height = 200 } = {}) {
  console.log( `${title} ${width} ${height}` );
}

show(); // title 100 200
show({width: 200}) // title 200 200

解析赋值

// key变量重命名, first --> firstName
const person = {
  first: 'foo',
  last: 'tom',
};

const { first: firstName } = person;
console.log(firstName); // foo
// 默认值
const settings = {
    speed: 150
}
const { speed = 750, width = 500 } = settings;
console.log(speed); // 150 
console.log(width); // 500

// 可能不存在的key
const { middle: middleName = 'midname' } = person;
console.log(middleName); // 'midname'
// 嵌套赋值
const user = {
  id: 339,
  name: 'Fred',
  age: 42,
  education: {
    degree: 'Masters'
  }
};
const {education: {degree}} = user;
console.log(degree); //prints: Masters
// 如果嵌套的属性不存在
const user = {
  id: 339,
  name: 'Fred',
  age: 42
};
const {education: {degree}} = user;  // TypeError: Cannot match against 'undefined' or 'null'.

// 解决办法:
const user = {
  id: 339,
  name: 'Fred',
  age: 42
};
const {education: {degree} = {}} = user;
console.log(degree); //prints: undefined

利用数组生成一个数字序列

const numRange = (start, end) => {
  return Array(end - start + 1).fill().map((item, index) => start + index);
};

const numbers = numRange(0, 5); // [0, 1, 2, 3, 4, 5]
const numbers2 = numRange(1, 5); // [1, 2, 3, 4, 5]

利用Set给数组去重

const years = [2016, 2017, 2017, 2018, 2018, 2019]

// set构造函数的参数是一个array
const distinctYears = [...new Set(years)] // [2016, 2017, 2018, 2019]

生成唯一随机字符串,可以指定长度

function generateRandom(length) {
    let radom13chars = function () {
        return Math.random().toString(16).substring(2, 15)
    }
    let loops = Math.ceil(length / 13)
    return new Array(loops).fill(radom13chars).reduce((string, func) => {
        return string + func()
    }, '').substring(0, length)
}

generateRandom(8) // "03836a49"

ES6+好用的小技巧,让你的代码更干净,短巧,易读


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

图解物联网

图解物联网

[ 日] NTT DATA集团、河村雅人、大塚纮史、小林佑辅、小山武士、宫崎智也、石黑佑树、小岛康平 / 丁 灵 / 人民邮电出版社 / 2017-4 / 59.00元

本书图例丰富,从设备、传感器及传输协议等构成IoT的技术要素讲起,逐步深入讲解如何灵活运用IoT。内容包括用于实现IoT的架构、传感器的种类及能从传感器获取的信息等,并介绍了传感设备原型设计必需的Arduino等平台及这些平台的选择方法,连接传感器的电路,传感器的数据分析,乃至IoT跟智能手机/可穿戴设备的联动等。此外,本书以作者们开发的IoT系统为例,讲述了硬件设置、无线通信及网络安全等运用Io......一起来看看 《图解物联网》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具