我的代码:
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;
谁能告诉我哪里弄错了?
答案 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
时进行初始化。
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;
您还可以使用Array.prototype.reverse
(link)来反转数组的数组,如代码段所示。
答案 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
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;
答案 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)));