0%

JS 利用函数做循环条件

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var stepCondition = function(current, end, step) {
if (step > 0) {
return current < end
/* 下面两种是经常能看到的反例
if(current < end) {
return true
} else {
return false
}
return current < end ? true : false */
} else {
return current > end
}
}

/* start end step 都是数字
要求支持负数 step
使用 while 循环
返回一个 array
假设 start=1, end=5, step=1 返回数据如下
[1, 2, 3, 4]
假设 start=6, end=0, step=-1 返回数据如下
[6, 5, 4, 3, 2, 1] */
var range3 = function(start, end, step=1) {

var l = []
var i = start
// 简单的办法是根据 step 写不同的条件
// 我这里用了一个辅助函数
while(stepCondition(i, end, step)) {
l.push(i)
i += step
}
return l
}