最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - OmitSkip a parameter with default value while calling a function in JS - Stack Overflow

programmeradmin2浏览0评论

In python we can omit a parameter with its default value in a function call. e.g.

def post(url, params={}, body={}):
    print()
    print(url)
    print(params)
    print(body)

post("http://localhost/users")

post("http://localhost/users", {"firstname": "John", "lastname": "Doe"})           # Skipped last argument (possible in JS as well)
post("http://localhost/users", params={"firstname": "John", "lastname": "Doe"})    # same as above

post("http://localhost", body={"email": "[email protected]", "password": "secret"})   # Skipped 2nd argument by passing last one with name (i.e. "body")

Can I achieve this in JS? Like omitting the 2nd argument and just pass the last one. (As in the last case). Other cases are possible in JS but I can't find a way to achieve the last one

In python we can omit a parameter with its default value in a function call. e.g.

def post(url, params={}, body={}):
    print()
    print(url)
    print(params)
    print(body)

post("http://localhost/users")

post("http://localhost/users", {"firstname": "John", "lastname": "Doe"})           # Skipped last argument (possible in JS as well)
post("http://localhost/users", params={"firstname": "John", "lastname": "Doe"})    # same as above

post("http://localhost", body={"email": "[email protected]", "password": "secret"})   # Skipped 2nd argument by passing last one with name (i.e. "body")

Can I achieve this in JS? Like omitting the 2nd argument and just pass the last one. (As in the last case). Other cases are possible in JS but I can't find a way to achieve the last one

Share Improve this question asked Oct 30, 2019 at 13:59 TalESidTalESid 2,5341 gold badge24 silver badges47 bronze badges 1
  • Possible duplicate of [Skip arguments in a JavaScript function ](stackoverflow./questions/32518615/…) – rassar Commented Oct 30, 2019 at 14:05
Add a ment  | 

2 Answers 2

Reset to default 4

You can achieve that by object destructions:

function post({ param1, param2 = "optional default value", param3 , param4}){
 /// definitions
}

let param3 = 'abc';
post({param1: 'abc', param3})

You cant ommit a parameter and call it by its name. Omitting in js would mean to pass undefined so if your post was a 3 argument function you would do

post('http://whatever', undefined,'somebody')

So that the second param takes the default value

However what you can do is take an object as the parameter, destructure and assign default values:

function post({url,params={},body={}}){
}

Then to call the function you would do post({url:'http://whatever',body:'somebody'});

发布评论

评论列表(0)

  1. 暂无评论