JavaScript统计整数末尾零个数时无法中断map循环怎么办
问题根因
代码中使用Array.prototype.map()执行遍历是核心问题:map、forEach这类内置数组迭代方法默认会遍历全部元素,回调函数内的return仅能终止当前单次回调的执行,无法中断整个遍历流程。因此遇到非零字符时,只是跳过了当次的计数逻辑,遍历仍会继续执行,导致统计到非零位之后的0值。
修复方案
方案1:使用支持中断的for循环(逻辑最直观)
const endZeros = (value) => { const stringValue = `${value}` const arrValue = stringValue.split("").reverse() let total = 0; for (const el of arrValue) { if (el === "0") { total++ } else { break // 碰到非零字符直接终止整个循环 } } return total; }
方案2:利用every方法的短路特性
every方法只要回调返回false就会立刻终止遍历,适配当前需求:
const endZeros = (value) => { const stringValue = `${value}` const arrValue = stringValue.split("").reverse() let total = 0; arrValue.every(el => { if (el === "0") { total++ return true // 满足条件继续遍历 } return false // 不满足直接终止遍历 }) return total; }
精简方案:正则匹配实现
无需手动遍历,直接匹配末尾连续0即可:
const endZeros = (value) => (`${value}`.match(/0*$/)?.[0] || '').length
以上方案调用endZeros(100100)均会返回正确结果2。
内容的提问来源于stack exchange,提问作者Verónica MF
相关产品推荐
相关产品推荐

