JavaScript数组计数

时间:2017-08-22 08:28:03

标签: javascript arrays

每个人,我在我的代码中遇到了一些问题,我想让他们倒数。但是,不知道为什么它会如下:

我的代码:



var countx = [];

function range(start, end, step) {
  if (step === undefined) {
    step = 1;
    for (var i = start; i <= end; i += step)
      countx.push(i);
    return countx;
  } else {
    for (var y = start; y >= end; y += step)
      countx.push(y);
    return countx;
  }
}

console.log(JSON.stringify(range(1, 10))); // -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

console.log(JSON.stringify(range(5, 2, -1))); // -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3, 2]
&#13;
&#13;
&#13;

谁能告诉我哪里弄错了?

3 个答案:

答案 0 :(得分:1)

这是因为你的countx变量。

当您第一次执行range时,countx就像您预期的那样[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]。但是当你再次执行它时,你会不断将新值推送到countx,因此你有[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3, 2]

为了解决这个问题,请将countx放入函数中,以便将变量限定为函数,并在每次执行range时进行初始化。

&#13;
&#13;
function range(start, end, step) {
  let countx = [];
  if (step === undefined) {
    step = 1;
    for (var i = start; i <= end; i += step)
      countx.push(i);
    return countx;
  } else {
    for (var y = start; y >= end; y += step)
      countx.push(y);
    return countx;
  }
}

console.log(JSON.stringify(range(1, 10))); // -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

console.log(JSON.stringify(range(5, 2, -1))); // -> [5, 4, 3, 2]

console.log(JSON.stringify(range(1, 10).reverse()))
&#13;
&#13;
&#13;

您还可以使用Array.prototype.reverselink)来反转数组的数组,如代码段所示。

答案 1 :(得分:1)

你应该在你的函数中声明你的数组,或者在调用函数之后它仍会保留它的数据。

在第一次range()致电之前:countx = []

第一次range()致电后:countx = [1,2,3,4,5,6,7,8,9,10]

在第二次range()致电之前:countx = [1,2,3,4,5,6,7,8,9,10] //Here is the problem

&#13;
&#13;
function range(start, end, step) {
  let countx = [];
  if (step === undefined) {
    step = 1;
    for (var i = start; i <= end; i += step)
      countx.push(i);
    return countx;
  } else {
    for (var y = start; y >= end; y += step)
      countx.push(y);
    return countx;
  }
}

console.log(JSON.stringify(range(1, 10)));

console.log(JSON.stringify(range(5, 2, -1)));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用单个循环并检查条件。

function range(start, end, inc) {
    var i, result = [];
    inc = inc || Math.abs(end - start) / (end - start) || 1;
    for (i = start; inc > 0 ? i <= end : i >= end; i += inc) {
        result.push(i);
    }
    return result;
}

console.log(JSON.stringify(range(1, 10)));
console.log(JSON.stringify(range(5, 2)));
console.log(JSON.stringify(range(7, 7)));