关于函数默认值的问题?

想这样的一个函数,使用了默认值,
但是我想传入flag这个变量为false
其他采用默认值
该如何实现,或者说该如何调用这个函数

 query(pageIndex = this.pageIndex,isOverseas = this.isOverseas,isSen=this.isSen, ip = this.ip,traffic= this.traffic,system=this.system,time=this.time, flag = true)
阅读 1.6k
3 个回答

没办法,JS 不支持类似其他语言中的命名参数写法:

function func(arg1 = null, arg2 = null, arg3 = null) {
}

func(arg3: true); // wrong

但我建议你需要传三个以上参数的时候就不要这么写,应换成对象形式传入,配置 Object.assign 来设置默认值,这样无论是可读性还是可扩展性都会好很多:

function query(options = {}) {
   options = Object.assign({
        pageIndex: this.pageIndex,
        isOverseas: this.isOverseas,
        isSen: this.isSen, 
        ip: this.ip,
        traffic: this.traffic,
        system: this.system,
        time: this.time, 
        flag: true
   }, options, {});
}

query({ flag: false }); // correct

P.S. 换成对象形式后也可以直接在函数参数里写默认值,但没有 Object.assign 兼容性好。

function fn({pageIndex = 1,isOverseas = 2,flag = true} = {}){
console.log(flag)
}
fn();//true
fn({flag:false}) //flase

可以改成传入的是一个对象:

const query = ({
    pageIndex = this.pageIndex,
    // ...
    flag = true
} = {}) = {
    // ...
};

query({ flag: false });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题