我目前正在关注Eloquent Javascript的练习,并且在一次练习中遇到了一些困难。让我用代码解释一下:
var _numberArray = [];
function range(start, end, step)
{
console.log(_numberArray);
if (!step)
{
step = 1;
}
if (step < 0)
{
for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);
}
}
else
{
for(var i = start; i <= end; i += step)
{
_numberArray.push(i);
console.log(_numberArray);
}
}
return _numberArray;
}
function sum(array)
{
var total = 0;
for (var i = 0; i < array.length; i++)
{
total += array[i];
}
return total;
}
console.log(sum(range(42,14,-2)));
所以我创建了range函数,我在其中检查是否已经设置了step参数。如果不是,则将默认步长变量设置为1.如果step小于0,则确保循环在第一个参数大于第二个参数的位置,并使用给定的步长量减小该值。增量也是如此。
但是,此代码仅在我使用负值时才会崩溃。所以当我做&#34; sum(范围(22,6,-2));&#34;代码崩溃了。反过来&#34;总和(范围(6,22,2));&#34;它确实有效。当我更换时:
for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);
}
对于:
for(var i = start; i >= end; i--)
{
_numberArray.push(i);
console.log(_numberArray);
}
它再次起作用!有人可以帮助我,让我理解为什么它会崩溃以及为什么最后一种方法有效?
感谢。
答案 0 :(得分:2)
由于步骤值为负值,并且您向下迭代,因此您需要添加它,而不是减去它:
for(var i = start; i >= end; i += step)
减去-2与添加2相同,所以你要去42,44,46 ......而且这个值总是超过&#34;结束&#34; (14),因此无限循环。
答案 1 :(得分:0)
if (step < 0)
{
for(var i = start; i >= end; i -= step)
如果,例如,step为负2,则start为22,end为6:
i = 22, 22 >= 6, i = 22 - (-2)
i = 24, 24 >= 6, i = 24 - (-2)
i = 26...
看起来你要考虑两次否定步骤(步骤是否定的,所以你不需要减去它)。
答案 2 :(得分:0)
我想出了一个解决问题的解决方案,用负数和一个消极步骤解决问题,也修改了一点功能,这样你就不会有两个for循环,而只是on while循环。
function range(n1,n2,step){
var start, end;
var list = [];
/*
Function take two parameters and decides which will become
the start by comparing both and evaluating who is smaller.
I used the ternary operator to test an expression if true
the first option is applied else the second option.
*/
(n1 > n2 ? (start = n2, end = n1):(start = n1, end = n2));
//Check if step is null or zero
if(step == null || step == 0)
step = 1;
/*
Check if step is a negative number, if so convert it to a
postive number. Since the start will always be the smallest
number there is no need to subtract even if the var start and
var end are both negative numbers
*/
if(step < 0)
step *= -1;
// Use a while loop to push numbers into array
while(start <= end){
list.push(start);
start += step;
}
// Made sure the var end was always included at the end of the list
if(list.indexOf(end) == -1)
list.push(end);
// Return list and end program
return list;
}
//funciton that adds up the list of numbers
function sum(array){
var total = 0 ;
for(var i = 0; i < array.length; i++){
total += array[i];
}
return total;
}