首页 > 解决方案 > javascript如何跳过为方法传递参数?

问题描述

最近一直在学习node.js,发现了两个这样的代码片段:

片段 1:

const fs = require('fs')
fs.readFile("content.txt", "utf8", (err, msg) => {
    console.log(msg);
})

片段 2:

const fs = require('fs')
fs.readFile("content.txt", (err, msg) => {
    console.log(msg);
})

它们只有一个区别,即Fragment 1将 'utf8' 作为第二个参数传递,而Fragment 2跳过传递它。尽管它们的结果不同,但它们都可以正常运行而不会出现语法错误。

所以我想知道javascript方法如何能够跳过传递参数?我怎样才能定义这样的方法/函数?

标签: javascriptnode.js

解决方案


您可以通过确定方法中的数量来在自己的代码中实现此效果。这可能就像检查参数的数量一样简单,或者您可能需要检查每个/某些参数的类型

一个例子:

function myArityAwareFunction(){
    if(arguments.length == 2)
        console.log("2 arguments", ...arguments)
    else if(arguments.length == 3)
        console.log("3 arguments", ...arguments)
    else
        throw ("This method must be called with 2 or 3 arguments");
}


myArityAwareFunction("foo","bar");
myArityAwareFunction("foo","bar","doo");
myArityAwareFunction("This will fail");


推荐阅读