【发布时间】:2022-11-16 11:32:46
【问题描述】:
我发现这段代码将 excel 列名转换为列号,但很难理解循环的中断条件
//function convert excel sheet column to number
toColumnNumber = (colName) => {
let result = 0;
for (let i = colName.length, j = 0; i--; j++) {
result += Math.pow(26, i) * (colName.charCodeAt(j) - 64);
}
return result;
};
console.log(toColumnNumber("AB"));
它使用 i-- 作为中断条件,我不明白如何使用它来中断循环。或者这就是当我们使用 i-- 作为中断条件并且它达到 0 时 javascript 的工作方式它打破了循环?
【问题讨论】:
-
0被认为是 false,因此当i变为 0 时循环中断。i > 0将更具可读性 -
在 Javascript 中,
0、"" (empty string)、undefined、null和NaN是虚假值。他们都等于假。 -
for ([declarations]; [conditional test]; [interations]) 你的循环开始时 i 设置为长度,j 设置为零,循环运行然后测试条件,如果为真,它运行交互并再次循环。所以是的,它正在倒数到零。
标签: javascript for-loop