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

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

这在JavaScript中有效吗?

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

当前回答

如果出于某种原因,您不在ES6上,并且正在使用lodash,那么这里有一种通过_.defaultTo方法默认函数参数的简洁方法:

var fn=函数(a,b){a=_.defaultTo(a,'Hi')b=_.defaultTo(b,'妈妈!')控制台日志(a,b)}fn()//嗨,妈妈!fn(未定义,空)//嗨,妈妈!fn(NaN,NaN)//嗨,妈妈!fn(1)//1“妈妈!”fn(空,2)//高2fn(假,假)//假-假fn(0,2)//0 2<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js“></script>

如果当前值为NaN、null或undefined,将设置默认值

其他回答

对于任何有兴趣在MicrosoftEdge中使用代码的人,不要在函数参数中使用默认值。

function read_file(file, delete_after = false) {
    #code
}

在该示例中,Edge将抛出错误“Expected')'”

为了避免这种使用

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

截至2016年8月8日,这仍然是一个问题

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

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

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

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

export const getfilesize = (bytes, decimals = 2) => {
    if (bytes === 0){ 
        return '0 Bytes';
    }else{
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];

    }
}
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!!!
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。这种方法在编程上看起来没有吸引力,但具有向后兼容性。