I am trying to create a function that takes in two vairables a
and b
, this function will create an array with variable a
reapeated b
times.
这是我走了多远,但未在数组中输出正确数量的项目:
var createArr = function(a, b) {
// returns an array with variable a repeated b times.
if (typeof b == 'number') {
var arr = [];
for (var i = 0; i <= b; i++) {
arr.push(a);
};
}
return arr;
};
createArr("ready",3)
for loop break will be
<
not<=
简单:
如果您将<=和“ b”的值设为“ 3”,则循环将针对0、1、2和3运行一次。糟糕,这是4次。
相反,您想使用<,因此循环将针对0、1,然后2而不是针对3运行一次。
See also https://en.wikipedia.org/wiki/Fencepost_error