【问题标题】:breaking a for loop with length decrement打破一个长度递减的for循环
【发布时间】: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)undefinednullNaN 是虚假值。他们都等于假。
  • for ([declarations]; [conditional test]; [interations]) 你的循环开始时 i 设置为长度,j 设置为零,循环运行然后测试条件,如果为真,它运行交互并再次循环。所以是的,它正在倒数到零。

标签: javascript for-loop


【解决方案1】:

当我们不断递减 I 的值时,最终它会达到 0,这将是错误的并会停止循环。

这只是一种奇特的说法:

for (let i = colName.length, j = 0; i > 0; j++, i--) {
    result += Math.pow(26, i) * (colName.charCodeAt(j) - 64);
  }

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多