功能需要和不需要的变量 [英] Function required and not-required variables

查看:127
本文介绍了功能需要和不需要的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我们可以在函数中指定变量的默认值,如:

  function myFunction(myDefaultVariable,myOtherVariable,myCheckVariable =基本){
//所以是的,myDefaultVariable总是需要的,
//同样适用于myOtherVariable,
//并且myCheckVariable可以在函数调用中被跳过,因为它有一个默认值已经指定。
}

有没有类似于JavaScript的东西?

$ b $你不需要在Javascript中传递所有的变量。



尽管不那么hacky方法是使用对象:

  function foo(args){
var text = args.text || '酒吧';

alert(text);
}

调用它:

  foo({text:'Hello'}); //会提醒你好
foo(); //如果args.text为空,它会在Bar被分配时提醒它


In PHP we can specify default value of variable in function like:

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
    // so yeah, myDefaultVariable is required always,
    // same applies for myOtherVariable,
    // and myCheckVariable can be skipped in function call, because it has a default value already specified.
}

Is there something similar to this in JavaScript?

解决方案

You don't need to pass all the variables in Javascript.

Although a less hacky way would be to use objects:

function foo(args) {
    var text = args.text || 'Bar';

    alert(text);
}

To call it:

foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null

这篇关于功能需要和不需要的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆