一. Function
1. 默认参数
(1). ES5的写法
{ function foo(x, y) { y = y || 'world' console.log(x, y) } foo('hello', 'imooc') foo('hello', 0) //输出hello world foo('hello') //输出hello world }
(2). ES6的写法
{ function foo(x, y = 'world') { console.log(x, y) } foo('hello', 0) //输出hello 0 foo('hello') //输出hello world }
PS: 函数参数是从左到右解析,如果没有默认值会被解析成 undefined,如果我们想让具体某个参数使用默认值,我们可以使用 undefined 进行赋值,如下段代码所示:
function f(x, y = 7, z = 42) { return x + y + z } console.log(f(1, undefined, 43)) // 51
在ES6中我们不仅可以给参数默认赋值具体的数值,同时参数赋值支持参数的逻辑运算进行赋值,如下段代码所示:
function f(x, y = 7, z = x + y) { return z * 0.5 } console.log(f(1, 7)) // 4 function ajax(url, { body = '', method = 'GET', headers = {} } = {}) { console.log(method) } ajax('http://www.imooc.com', { method: 'POST' })