这是lodash的源代码:
const MAX_SAFE_INTEGER = 9007199254740991
const MAX_ARRAY_LENGTH = 4294967295
function times(n, iteratee) {
if (n < 1 || n > MAX_SAFE_INTEGER) {
return []
}
let index = -1
const length = Math.min(n, MAX_ARRAY_LENGTH)
const result = new Array(length)
while (++index < length) {
result[index] = iteratee(index)
}
index = MAX_ARRAY_LENGTH
n -= MAX_ARRAY_LENGTH
while (++index < n) {
iteratee(index)
}
return result
}
我最困惑的是最后一部分:
index = MAX_ARRAY_LENGTH
n -= MAX_ARRAY_LENGTH
while (++index < n) {
iteratee(index)
}
我这样做的目的是确保iteratee
在n
和n
之间时,MAX_ARRAY_LENGTH
调用MAX_SAFE_INTEGER
次。
此时,代码应为:
while (++index < n) {
iteratee(index)
}
所以为什么lodash让n -= MAX_ARRAY_LENGTH
。
这是功能还是错误?