如何打印字符串并生成匹配其长度的字符位置标尺?
动态生成匹配字符串长度的字符位置标尺用于调试
为了加快调试效率,需要在打印字符串时,在其下方显示对应的字符位置标尺,效果示例如下:
a string with its characters' positions below it 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 1 2 3 4
固定长度的标尺无法适配不同长度的字符串,这里提供一个动态生成适配长度标尺的JavaScript实现:
function logWithPositionRuler(str) { // 高亮打印原字符串,便于对齐查看 console.debug(`%c${str}`, 'background-color: yellow'); // 生成第一行标尺:偶数索引显示个位数字,奇数索引显示空格 const firstLine = Array.from(str).map((_, idx) => { const digit = idx % 10; return digit % 2 === 0 ? digit : ' '; }).join(' '); // 生成第二行标尺:每10个字符显示对应十位数字,其余位置为空格 const secondLine = Array.from(str).map((_, idx) => { if ((idx + 1) % 10 === 0) { return Math.floor((idx + 1) / 10); } return ' '; }).join(' '); console.debug(firstLine); console.debug(secondLine); } // 使用示例 const testString = "a string with its characters' positions below it"; logWithPositionRuler(testString);
逻辑说明
- 第一行标尺:对应字符串的每个字符位置,仅在偶数索引(0、2、4...)显示该位置的个位数字,奇数索引用空格填充,确保和原字符串的字符一一对齐。
- 第二行标尺:在每第10、20、30...个字符的位置显示对应的十位数字(1、2、3...),其余位置用空格填充,直观标记出十位级别的位置。
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

