一. 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'
})
View Code

相关文章:

  • 2022-02-12
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2022-01-06
猜你喜欢
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
  • 2021-08-10
相关资源
相似解决方案