javascript - 参数可选

标签 javascript

目前我正在开发 freeCodeCamp challenge 。我宁愿复制/粘贴挑战本身,也不愿自己写。

Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5.

If either argument isn't a valid number, return undefined.

这是我创建的解决方案:

function addTogether(a) {
  for (let j = 0; j < arguments.length; j++){
    // console.log(typeof(arguments[j]));
    if(typeof(arguments[j]) != "number"){
      return undefined;
    } else if (typeof(arguments[j]) == 'string') {
      return undefined;
    } else {
      console.log('go up');
      if (arguments.length >= 2){
        let sum = 0;
        for(let i = 0; i < arguments.length; i++){
          sum += arguments[i];
        }
        return sum;
      }
    }
  }

  return function(b){
    if (typeof(b) == 'object'){
      return undefined;
    } else {
      return a + b;
    }
  }
}

这个解决方案的正确率是 80%,但它无法处理 addTogether(2, "3") 应该返回未定义的情况。 尽管我添加了此检查 typeof(arguments[j] ) == '字符串'。我该如何让它发挥作用?谢谢。

最佳答案

尝试调用addTogether()

function addTogether(a, b) {
  if(typeof(a) !== 'number' || (b != undefined && typeof(b) !== 'number')) {
    return undefined;
  }
  if(b == undefined) {
    return c => addTogether(a, c);
  }
  return a + b;
}

addTogether(2,3);

关于javascript - 参数可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864666/

相关文章:

javascript - 使用 TS 的 Angular2 中的安全性

javascript - 将副本添加到索引模板上的elasticsearch

javascript - 在 div 中重新执行硬编码的外部 JavaScript

javascript - Ember-charts 导致无法在对象上找到属性 'pie-chart'

javascript - 如何从嵌套的 FormGroup 添加/删除 FormControl

javascript - 带有输入掩码的 jQuery 验证

javascript - Safari ITP 2.0 存储访问 API - 在 hasStorageAccess 中嵌套 requestStorageAccess 时出现问题 - 非嵌套工作

javascript - 如果电子邮件在 Gmail 的主题或正文中包含特定字词,则使用脚本对其进行标记

javascript - 使用url编码转换特殊字符(é è ë)

javascript - 从 Highcharts 中的 HTML 表中解析日期