Sum of range---getting "undefined"

时间:2018-02-19 16:47:24

标签: javascript arrays function for-loop range

I'm looking for the sum of a range but I keep getting "undefined." I believe something's in the wrong spot but I'm not sure as to what it is.

Part 1: "Write a range function that takes two arguments, start and end, and returns an array containing all of the numbers from start up to (and including) end:

Part 2: "Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55."

// Part 1
function deRange(start, end, step) {

  if (step === null) {
    step = 1;

    var blank = [];

    if (step > 0) {
      for (var i = start; i <= end; i += step)
        blank.push(i);
    } else {
      for (var i = start; i >= end; i += step)
        blank.push(i);
    }
  }
  return blank;
}

// Part 2
function theSum(blank) {
  var total = 0;
  for (var i = 0; i < blank.length; i++)
    total += blank[i];
  return total;
}

console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));

2 个答案:

答案 0 :(得分:1)

你错放了大括号。这有效:

&#13;
&#13;
function range(start, end, step) {
  if (step === null) {
    step = 1;
  }
  var blank = [];
  if (step > 0) {
    for (var i = start; i <= end; i += step)
      blank.push(i);
  } else {
    for (var i = start; i >= end; i += step)
      blank.push(i);
  }
  return blank;
}
console.log(range(1, 5, null));
&#13;
&#13;
&#13;

请注意,您正在检查step是否为null,因此用户仍需要明确指定null作为参数。如果要在未提供第三个参数的情况下设置默认值,请使用例如:

step = step || 1;

(这也将0视为缺失的参数,这很好。)

答案 1 :(得分:0)

下面我修复了你的代码并评论了你的一些错误。查看演示。

// Part 1
function deRange(start, end, step) {

  /**
   * If you want to make sure 'step' is not 0 (zero) either,
   * change the if like this:
   * if(!step) { step = 1; }
   */
  if (step === null || typeof step === 'undefined') { // <- also check when 'step' was not passed as argument
    step = 1;
  } // <-- curly brace here!
  var blank = [];

  if (step > 0) {
    for (var i = start; i <= end; i += step)
      blank.push(i);
  } else {
    for (var i = start; i >= end; i += step)
      blank.push(i);
  }
  return blank;
}

// Part 2
function theSum(blank) {
  var total = 0;
  for (var i = 0; i < blank.length; i++)
    total += blank[i];
  return total;
}

console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));