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

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

这在JavaScript中有效吗?

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

当前回答

设置默认参数的另一种方法是使用参数的对象映射,而不是直接使用参数。例如

const defaultConfig = {
 category: 'Animals',
 legs: 4
};

function checkOrganism(props) {
 const category = props.category || defaultConfig.category;
 const legs = props.legs || defaultConfig.legs;
}

这样,很容易扩展参数,而不用担心参数长度不匹配。

其他回答

作为更新。。。使用ECMAScript 6,您最终可以在函数参数声明中设置默认值,如下所示:

function f (x, y = 7, z = 42) {
  return x + y + z
}

f(1) === 50

参考文件:http://es6-features.org/#DefaultParameterValues

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

以下代码可能在这种情况下工作,包括ECMAScript 6(ES6)以及早期版本。

函数read_file(文件,删除后){if(delete_after==未定义)delete_after=false//默认值console.log('delete_after=',delete_after);}read_file('text1.txt',true);读取文件('text2.txt');

由于语言中的默认值在调用时跳过函数的参数值时起作用,因此在JavaScript中它被分配给undefined。这种方法在编程上看起来没有吸引力,但具有向后兼容性。

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!!!

在ECMAScript 6中,您实际上可以编写您所拥有的内容:

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

如果delete_after不存在或未定义,则会将其设置为false。您可以在Babel等转发器上使用像今天这样的ES6功能。

有关更多信息,请参阅MDN文章。

ES6:正如大多数答案中已经提到的,在ES6中,您可以简单地初始化一个参数和一个值。


ES5:大多数给出的答案对我来说都不够好,因为在某些情况下,我可能不得不向函数传递假值,例如0、null和undefined。要确定参数是否未定义,因为这是我传递的值,而不是未定义的值,因为根本没有定义,我执行以下操作:

function foo (param1, param2) {
   param1 = arguments.length >= 1 ? param1 : "default1";
   param2 = arguments.length >= 2 ? param2 : "default2";
}