[英]Why does the result array start with 0 rather than 1?
Shouldn't i be pushing 1 to my result array for the first iteration if start = 0?如果 start = 0,我不应该将 1 推送到我的结果数组进行第一次迭代吗?
function getEveryOtherNumber(start, end) {
let resultArr = [];
while (start < end) {
resultArr.push(start++);
start++;
}
return resultArr;
}
console.log(getEveryOtherNumber(0, 10)); // => [ 0, 2, 4, 6, 8 ]
start++
the postfix operator returns the value of start and then increments. start++
后缀运算符返回 start 的值,然后递增。
++start
the prefix operator increments the value of start and then returns. ++start
前缀运算符递增 start 的值,然后返回。
You are looking for the second one:)您正在寻找第二个:)
because start starts at 0, and start++
assigns the value AFTER pushing.因为 start 从 0 开始,并且
start++
在 push 之后分配值。
if you want to do it before, use ++start
.如果您想以前这样做,请使用
++start
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.