我希望JavaScript函数具有可选的参数,我在这些参数上设置了默认值,如果未定义值,则使用这些参数(如果传递了值,则忽略这些参数)。在Ruby中,您可以这样做:

def read_file(file, delete_after = false)
  # code
end

这在JavaScript中有效吗?

function read_file(file, delete_after = false) {
  // Code
}

当前回答

如果您想使用最新的ECMA6语法,请使用此选项:

函数myFunction(someValue=“这是默认值!”){console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数

它被称为默认函数参数。如果没有传递值或未定义,它允许使用默认值初始化形式参数。注意:它不适用于Internet Explorer或较旧的浏览器。

为了获得最大可能的兼容性,请使用以下选项:

函数myFunction(someValue){someValue=(someValue==未定义)?“这是默认值!”:someValue;console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数

这两个函数具有完全相同的行为,因为这些示例依赖于这样一个事实:如果在调用该函数时没有传递任何参数值,则参数变量将是未定义的。

其他回答

是的,这将在Javascript中工作。您也可以这样做:

function func(a=10,b=20)
{
    alert (a+' and '+b);
}

func(); // Result: 10 and 20

func(12); // Result: 12 and 20

func(22,25); // Result: 22 and 25
function helloWorld(name, symbol = '!!!') {
    name = name || 'worlds';
    console.log('hello ' + name + symbol);
}

helloWorld(); // hello worlds!!!

helloWorld('john'); // hello john!!!

helloWorld('john', '(>.<)'); // hello john(>.<)

helloWorld('john', undefined); // hello john!!!

helloWorld(undefined, undefined); // hello worlds!!!

是的,ES6完全支持使用默认参数:

function read_file(file, delete_after = false) {
  // Code
}

or

const read_file = (file, delete_after = false) => {
    // Code
}

但在ES5之前,您可以轻松做到这一点:

function read_file(file, delete_after) {
  var df = delete_after || false;
  // Code
}

这意味着如果值存在,则使用该值,否则,在执行相同操作的||操作之后使用第二个值。。。

注意:如果你将一个值传递给ES6,它们之间也有很大的区别,即使值是假的,也会被新值替换,比如null或“”。。。但是ES5只有在传递的值为真时才会被替换,这是因为工作方式。。。

只需使用未定义的显式比较。

function read_file(file, delete_after)
{
    if(delete_after === undefined) { delete_after = false; }
}

根据语法

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

您可以定义正式参数的默认值。还可以使用typeof函数检查未定义的值。