简体   繁体   English

为什么结果数组以 0 而不是 1 开头?

[英]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.

相关问题 为什么这会导致串联而不是将两个数字相加? - Why does this result in concatenation rather than adding the two numbers together? 为什么此HTTP请求返回数组长度而不是内容长度? - Why does this HTTP request return array lengths rather than content? 为什么 document.querySelectorAll 返回一个 StaticNodeList 而不是一个真正的数组? - Why does document.querySelectorAll return a StaticNodeList rather than a real Array? 为什么Ajax将数据发布到localhost而不是提供的URL? - Why does Ajax post data to localhost rather than the provided URL? 为什么将字符串附加到Date调用toString()而不是valueOf()? - Why does appending a string to a Date invoke toString() rather than valueOf()? 为什么这个服务返回一个承诺而不是一个履行的承诺? - Why does this service return a promise rather than a fulfilled promise? 为什么重新分配工作而不是仅仅返回 concat? - Why does reassigning work rather than just returning in concat? 为什么验证对表单名称而不是模型起作用? - Why does validation work on form names rather than on the model? 为什么人们使用仅以//开头而不是http://或https://的网址 - Why do people use URLs that start with just // rather than with http:// or https:// 为什么我的Angular应用程序中的此表达式显示的是文字文本而不是评估表达式的结果? - Why is this expression in my Angular app displaying the literal text rather than the result of the evaluated expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM