【问题标题】:How can javascript skip passing a parameter for a method?javascript如何跳过为方法传递参数?
【发布时间】:2021-09-10 19:24:06
【问题描述】:

最近在学习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 方法如何能够跳过传递参数?我该如何定义这样的方法/函数?

【问题讨论】:

  • 调用函数时参数的数量是可选的。通常函数会按类型检查参数(这些函数可以传递不同数量的参数),然后根据特定参数的类型执行替代代码。
  • 该函数将确定参数的arity,并测试第二个参数是否为函数,然后根据该信息继续。
  • @Teemu 感谢您的回答,您的回答解决了我的困惑。

标签: javascript node.js


【解决方案1】:

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

一个例子:

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");

【讨论】:

  • 我认为 javascript 一定为我们实现了一些不错的语法,但我从来没有想过只有一堆 if 和 else if 这么简单,但是当有很多参数时事情会变得更复杂?
  • @Paper_Folding 也有默认的可选参数:jsfiddle.net/876Lv5pf
  • @Paper_Folding 请阅读此stackoverflow.com/questions/4633125/…
【解决方案2】:

带箭头功能:

const fn = (...args) => {
  console.log(args.length);
  if (args.length < 2) {
    throw Error('missing arguments');
  } else if (args.length === 2) {
    /* ... */
  } else if (args.length === 3) {
    /* ... */
  } else {
    /* ... */
  }
};

或使用switch

const fn = (...args) => {
  console.log(args.length);
  switch(args.length) {
    case 0: /* ... */ break;
    case 1: /* ... */ break;
    /* ... */
    default: /* ... */ break;
  }
};

但验证参数类型比依赖args.length 做某事要好得多

因此,对于您的示例,fs 代码可能如下所示:

const readFile = (...args) => {
  if (typeof args[0] === 'string') {
    /* ... */
  } else {
    throw TypeError('Path must be a string');
  }
  if (typeof args[1] === 'string') {
    /* ... */
    if (typeof args[2] === 'function') {
      /* ... */
    } else {
      throw TypeError('Callback must be a function');
    }
  } else if (typeof args[1] === 'function') {
    /* ... */
  } else {
    throw TypeError('Callback must be a function');
  }
};
readFile({}); // TypeError: path must be a string
readFile('test.txt', 'utf-8', {}); // TypeError: Callback must be a function
readFile('test.txt', {}); // TypeError: Callback must be a function

readFile('test.txt', () => {}); // success
readFile('test.txt', 'utf-8', () => {}); // success

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2011-10-14
    相关资源
    最近更新 更多