JavaScript ES6中的简写语法总结与使用技巧(8)
不过这种情况下,函数调用时,如果参数为空即carFactory()函数将抛出异常。这种问题可以通过下面的方法来修复,下述代码中我们添加了一个空对象作为options的默认值,这样当函数被调用时,如果参数为空,会自动以{}作为参数。
function carFactory({ brand = 'Volkswagen', make = 1999 } = {}) { console.log(brand) console.log(make) } carFactory() // <- 'Volkswagen' // <- 1999
除此之外,使用函数参数解构,还可以让你的函数自行匹配对应的参数,看接下来的例子,你就能明白这一点了,我们定义一个名为car的对象,这个对象拥有很多属性:owner,brand,make,model,preferences等等。
var car = { owner: { id: 'e2c3503a4181968c', name: 'Donald Draper' }, brand: 'Peugeot', make: 2015, model: '208', preferences: { airbags: true, airconditioning: false, color: 'red' } }
解构能让我们的函数方便的只使用里面的部分数据,下面代码中的函数getCarProductModel说明了具体该如何使用:
var getCarProductModel = ({ brand, make, model }) => ({ sku: brand + ':' + make + ':' + model, brand, make, model }) getCarProductModel(car)
解构使用示例
当一个函数的返回值为对象或者数组时,使用解构,我们可以非常简洁的获取返回对象中某个属性的值(返回数组中某一项的值)。比如说,函数getCoordinates()返回了一系列的值,但是我们只想用其中的x,y,我们可以这样写,解构帮助我们避免了很多中间变量的使用,也使得我们代码的可读性更高。
function getCoordinates() { return { x: 10, y: 22, z: -1, type: '3d' } } var { x, y } = getCoordinates()
通过使用默认值,可以减少重复,比如你想写一个random函数,这个函数将返回一个位于min和max之间的值。我们可以分辨设置min默认值为1,max默认值为10,在需要的时候还可以单独改变其中的某一个值:
function random({ min = 1, max = 10 } = {}) { return Math.floor(Math.random() * (max - min)) + min } console.log(random()) // <- 7 console.log(random({ max: 24 })) // <- 18
解构还可以配合正则表达式使用。看下面这个例子:
function splitDate(date) { var rdate = /(\d+).(\d+).(\d+)/ return rdate.exec(date) } var [ , year, month, day] = splitDate('2015-11-06')
不过当.exec不比配时会返回null,因此我们需要修改上述代码如下:
var matches = splitDate('2015-11-06') if (matches === null) { return } var [, year, month, day] = matches
内容版权声明:除非注明,否则皆为本站原创文章。