javascript - 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方法如何能够跳过传递参数?我怎样才能定义这样的方法/函数?
解决方案
您可以通过确定方法中的数量来在自己的代码中实现此效果。这可能就像检查参数的数量一样简单,或者您可能需要检查每个/某些参数的类型
一个例子:
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");
推荐阅读
- database - 你能帮我关于使用Android studio QR码扫描仪扫描QR码以在扫描QR码后将数据保存在DATABASE上吗
- button - 如何在 JavaFX 中使用多个按钮?
- python - 部署 Django 应用程序时出现 Heroku 错误 H10
- javascript - 由于数据加载而反应过多的重新渲染?
- python - Django 发送电子邮件:django.core.exceptions.ImproperlyConfigured 错误
- android - 如何更改如何从当前用户 uid 更改为 id 收据
- shell - 使用热键守护程序在同一密码中打开终端以打开新终端
- sql - 如何使用字段为字符串的 MAX 函数查找具有最高字段值的记录集?
- spring-boot - JsonIdentityReference 规范化 JPA 实体的 OpenApi 模式
- discord.py - 如何在 discord.ui 按钮组件中添加自定义表情符号