Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

关于函数默认值的问题?

想这样的一个函数,使用了默认值,
但是我想传入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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

没办法,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 兼容性好。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...