JavaScript padStart / padEnd:长度不是截断,填充也不是字符计数

10-22 5阅读
JavaScript padStart / padEnd:长度不是截断,填充也不是字符计数
独立模型生成的概念示意图,不是真实软件截图;方块只表达填充方向,不代表屏幕显示宽度。

给编号补零、给日志补点时,padStart 与 padEnd 很顺手;问题通常出在把它们当成“固定宽度裁剪器”或“字符排版器”。二者只把填充字符串加在开头或结尾,理解长度单位、转换顺序与提前返回条件,才能避免封装之后反而改变原生语义。

一、目标长度不是必须达到的最终长度

按 MDN padStart 与 MDN padEnd 的参数说明,目标长度不大于原串长度时,返回原串,不会截断。“cat”补到二位仍是“cat”。确实需要填充时,先计算缺口,把填充串重复,再从末尾截掉多余部分;被截短的是填充串,不是输入。

例如三位原串补到八位,缺口为五,填充串“ab”提供的前五位是“ababa”。另外,空填充串不会制造空格,而是直接返回原串。因此“返回值必定等于目标长度”本身就是错误断言。

二、这里的长度单位是 UTF-16 码元

ECMAScript 字符串定义按十六位元素计数。一个常见表情可能占两个码元;字母加组合重音也可能占两个码元,但肉眼看起来像一个字形。把 Array.from 的码点数量或屏幕列宽代入,都不是原生契约。

更隐蔽的是填充内容:表情重复后恰好需要截取奇数个码元,可能留下孤立代理项。渲染成替代符号不代表数据已被自动修复。面向用户的排版应另行定义字素簇、字体与显示宽度规则,不能把这些方法当作 Unicode 排版算法。

三、省略、undefined、null 不是同一种填充

省略第二个参数或明确传入 undefined,使用普通空格 U+0020;null 则会转换成四个字母“null”。数字零变成“0”,false 变成“false”。因此用逻辑或补默认值会误伤空字符串、零与 false;用空值合并也会把 null 的原生意义改掉。

长度参数走 ToLength 转换:有限正小数去掉小数部分,负数、NaN 与 undefined 得到零,数字字符串可以转换。本教程只测试小范围输入,不尝试巨大长度或无穷值,也不承诺任何引擎的内存上限与耗时。

四、先转换接收者,再转换长度,必要时才转换填充

规范中的公共实现先取得接收者的字符串,再转换长度;不需要填充就提前返回。只有存在缺口,才处理填充参数。因此带副作用的填充对象可能完全不被转换。这里说的是方法内部转换顺序,填充实参表达式本身仍会在调用前求值。

方法可以借给数字、BigInt 或普通对象使用,但 null 和 undefined 接收者会被拒绝。Symbol 不能按此路径转换成字符串;Symbol 与 BigInt 也不能作为长度。BigInt 却能作为接收者或填充内容。Symbol 填充只有真正需要转换时才报错;提前调用 String 或 Number 会改变这些边界。

五、四个可以独立运行的小例子

编号场景先约定非负安全整数,再补零。这里的三十二位上限是示例的业务限制,不是 JavaScript 的字符串长度上限;超出宽度的编号仍完整保留。

// Bounded non-negative safe integer IDs, not arbitrary numeric formatting.
function idText(value, width) {
  if (!Number.isSafeInteger(value) || value < 0 ||
      !Number.isInteger(width) || width < 0 || width > 32) {
    throw new RangeError("invalid ID or width");
  }
  return String(value).padStart(width, "0");
}
const actual = [idText(42, 5), idText(123456, 5)];
const expected = ["00042", "123456"];
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error("ID mismatch");
console.log(JSON.stringify(actual));

ASCII 日志标签可以右侧补点,但这不保证任意中文、表情或比例字体都能视觉对齐。

// These labels are ASCII; padEnd is not a screen-width algorithm.
const line = "GET".padEnd(6, ".") + " | " + "OK";
if (line !== "GET... | OK") throw new Error("line mismatch");
console.log(line);

检查表情填充时,直接读取码元能避免终端显示掩盖问题。下面最后一个数对应未配对的高代理项。

// Inspect code units instead of trusting how an isolated surrogate renders.
const padded = "x".padEnd(4, "\u{1F600}");
const units = Array.from({ length: padded.length }, (_, i) => padded.charCodeAt(i));
const expected = [120, 55357, 56832, 55357];
if (JSON.stringify(units) !== JSON.stringify(expected)) throw new Error("unit mismatch");
console.log(JSON.stringify(units));

负数不会自动把零放到符号后面。若业务规定总宽度包含负号,需要拆出符号再填充绝对值;此示例只处理安全整数,并把负零视作零,不承担小数、货币或本地化格式职责。

// Explicit domain rule: total width includes one minus sign.
function signedIntegerText(value, width) {
  if (!Number.isSafeInteger(value) || !Number.isInteger(width) || width < 1 || width > 32) {
    throw new RangeError("invalid signed integer or width");
  }
  const sign = value < 0 ? "-" : "";
  return sign + String(Math.abs(value)).padStart(width - sign.length, "0");
}
const actual = [String(-7).padStart(4, "0"), signedIntegerText(-7, 4)];
const expected = ["00-7", "-007"];
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error("signed mismatch");
console.log(JSON.stringify(actual));

六、用契约测试识别“看起来一样”的封装

下面完整脚本无需依赖。保存为 suite.cjs 后执行 node suite.cjs,即可运行两种上下文。四十个显式预期与七个反例在首次执行前冻结;实测 Node v24.19.0,普通与严格上下文均全部通过,四个短例也分别通过,没有事后改写预期。

严格上下文通过带有明确指令的 Function 重新解析整段测试函数,并用普通函数的 this 验证,而不是只给调用者加严格模式。反例覆盖强制裁剪、默认值替换、提前转换、误接收 Symbol 或 BigInt,以及改用码点计数;测试失败会明确抛出异常。

展开完整自包含测试:40 个案例与 7 个错误封装见证
// Save as suite.cjs and run: node suite.cjs
// Optional single context: node suite.cjs ordinary OR node suite.cjs strict
// All expectations were authored before the first execution.
function runSuite(mode, expectedStrict) {
  const actualStrict = (function () { return this; })() === undefined;
  if (actualStrict !== expectedStrict) throw new Error("lexical context mismatch");
  console.log("CONTEXT " + mode + " lexicalStrict=" + actualStrict);
  let passed = 0;
  function assertEqual(actual, expected, id) {
    if (actual !== expected) {
      throw new Error(id + " expected=" + JSON.stringify(expected) +
        " actual=" + JSON.stringify(actual));
    }
  }
  function capture(fn) {
    try { return "value:" + fn(); } catch (error) { return "throw:" + error.name; }
  }
  function bomb() { return { toString() { throw new Error("fill converted"); } }; }
  function conversionTrace(kind) {
    const seen = [];
    const receiver = {
      [Symbol.toPrimitive](hint) {
        seen.push("receiver:" + hint);
        if (kind === "receiver-error") throw new TypeError("receiver");
        return "x";
      }
    };
    const length = {
      [Symbol.toPrimitive](hint) {
        seen.push("length:" + hint);
        if (kind === "length-error") throw new RangeError("length");
        return kind === "skip" ? 1 : 3;
      }
    };
    const fill = {
      [Symbol.toPrimitive](hint) {
        seen.push("fill:" + hint);
        if (kind === "skip") throw new Error("must not run");
        return "0";
      }
    };
    let result;
    try { result = String.prototype.padStart.call(kind === "null" ? null : receiver, length, fill); }
    catch (error) { result = error.name; }
    return result + "|" + seen.join(",");
  }
  const cases = [
    { id: "C01", input: "start basic", run: () => "x".padStart(4, "0"), expected: "000x" },
    { id: "C02", input: "end basic", run: () => "x".padEnd(4, "0"), expected: "x000" },
    { id: "C03", input: "start no input truncation", run: () => "cat".padStart(2, "0"), expected: "cat" },
    { id: "C04", input: "end no input truncation", run: () => "cat".padEnd(2, "0"), expected: "cat" },
    { id: "C05", input: "start repeat then truncate", run: () => "cat".padStart(8, "ab"), expected: "ababacat" },
    { id: "C06", input: "end repeat then truncate", run: () => "cat".padEnd(8, "ab"), expected: "catababa" },
    { id: "C07", input: "long filler truncated", run: () => "cat".padStart(5, "abcdef"), expected: "abcat" },
    { id: "C08", input: "empty filler", run: () => "cat".padEnd(8, ""), expected: "cat" },
    { id: "C09", input: "omitted filler", run: () => "x".padStart(3), expected: "  x" },
    { id: "C10", input: "undefined filler", run: () => "x".padEnd(3, undefined), expected: "x  " },
    { id: "C11", input: "null filler", run: () => "x".padStart(6, null), expected: "nullnx" },
    { id: "C12", input: "number filler", run: () => "x".padStart(4, 0), expected: "000x" },
    { id: "C13", input: "boolean filler", run: () => "x".padStart(5, false), expected: "falsx" },
    { id: "C14", input: "fraction length", run: () => "x".padStart(4.9, "0"), expected: "000x" },
    { id: "C15", input: "negative length", run: () => "x".padEnd(-2.9, "0"), expected: "x" },
    { id: "C16", input: "NaN length", run: () => "x".padStart(NaN, "0"), expected: "x" },
    { id: "C17", input: "undefined length", run: () => "x".padEnd(undefined, "0"), expected: "x" },
    { id: "C18", input: "numeric string length", run: () => "x".padStart("4", "0"), expected: "000x" },
    { id: "C19", input: "null length", run: () => "x".padEnd(null, "0"), expected: "x" },
    { id: "C20", input: "boolean length empty source", run: () => "".padStart(true, "0"), expected: "0" },
    { id: "C21", input: "astral receiver length", run: () => "😀".padStart(3, "0"), expected: "0\ud83d\ude00" },
    { id: "C22", input: "combining sequence", run: () => "e\u0301".padEnd(3, "."), expected: "e\u0301." },
    { id: "C23", input: "cut emoji fill at start", run: () => "x".padStart(2, "😀"), expected: "\ud83dx" },
    { id: "C24", input: "cut emoji fill at end", run: () => "x".padEnd(4, "😀"), expected: "x\ud83d\ude00\ud83d" },
    { id: "C25", input: "number receiver", run: () => String.prototype.padStart.call(7, 3, "0"), expected: "007" },
    { id: "C26", input: "object receiver", run: () => String.prototype.padEnd.call({ toString() { return "cat"; } }, 5, "."), expected: "cat.." },
    { id: "C27", input: "null receiver", run: () => String.prototype.padStart.call(null, 2, "0"), expected: {"throws": "TypeError"} },
    { id: "C28", input: "undefined receiver", run: () => String.prototype.padEnd.call(undefined, 2, "0"), expected: {"throws": "TypeError"} },
    { id: "C29", input: "Symbol receiver", run: () => String.prototype.padStart.call(Symbol("s"), 1, "0"), expected: {"throws": "TypeError"} },
    { id: "C30", input: "BigInt receiver", run: () => String.prototype.padStart.call(12n, 4, "0"), expected: "0012" },
    { id: "C31", input: "Symbol length", run: () => "cat".padStart(Symbol("n"), "0"), expected: {"throws": "TypeError"} },
    { id: "C32", input: "BigInt length", run: () => "x".padStart(3n, "0"), expected: {"throws": "TypeError"} },
    { id: "C33", input: "Symbol filler when padding", run: () => "x".padEnd(3, Symbol("f")), expected: {"throws": "TypeError"} },
    { id: "C34", input: "Symbol filler skipped", run: () => "cat".padEnd(2, Symbol("f")), expected: "cat" },
    { id: "C35", input: "BigInt filler", run: () => "x".padStart(4, 12n), expected: "121x" },
    { id: "C36", input: "receiver length fill conversion order", run: () => conversionTrace("all"), expected: "00x|receiver:string,length:number,fill:string" },
    { id: "C37", input: "fill conversion skipped", run: () => conversionTrace("skip"), expected: "x|receiver:string,length:number" },
    { id: "C38", input: "null rejection before length conversion", run: () => conversionTrace("null"), expected: "TypeError|" },
    { id: "C39", input: "receiver exception stops conversion", run: () => conversionTrace("receiver-error"), expected: "TypeError|receiver:string" },
    { id: "C40", input: "length exception stops conversion", run: () => conversionTrace("length-error"), expected: "RangeError|receiver:string,length:number" }
  ];
  for (const test of cases) {
    if (typeof test.expected === "object") {
      let caught = null;
      try { test.run(); } catch (error) { caught = error; }
      if (caught === null) throw new Error(test.id + " expected an exception");
      assertEqual(caught.name, test.expected.throws, test.id);
    } else {
      assertEqual(test.run(), test.expected, test.id);
    }
    passed += 1;
    console.log("PASS " + test.id + " " + test.input);
  }
  const witnesses = [
    { id: "W01", label: "slice is not padding", native: () => "cat".padStart(2, "0"), wrong: () => ("0".repeat(2) + "cat").slice(-2), expectedNative: "value:cat", expectedWrong: "value:at" },
    { id: "W02", label: "truthy default destroys empty filler", native: () => "x".padEnd(3, ""), wrong: () => "x".padEnd(3, "" || " "), expectedNative: "value:x", expectedWrong: "value:x  " },
    { id: "W03", label: "nullish default destroys null conversion", native: () => "x".padStart(5, null), wrong: () => "x".padStart(5, null ?? " "), expectedNative: "value:nullx", expectedWrong: "value:    x" },
    { id: "W04", label: "eager filler conversion changes side effects", native: () => "cat".padStart(2, bomb()), wrong: () => "cat".padStart(2, String(bomb())), expectedNative: "value:cat", expectedWrong: "throw:Error" },
    { id: "W05", label: "Number incorrectly admits BigInt length", native: () => "x".padStart(3n, "0"), wrong: () => "x".padStart(Number(3n), "0"), expectedNative: "throw:TypeError", expectedWrong: "value:00x" },
    { id: "W06", label: "String incorrectly admits Symbol receiver", native: () => String.prototype.padStart.call(Symbol("s"), 1, "0"), wrong: () => String(Symbol("s")).padStart(1, "0"), expectedNative: "throw:TypeError", expectedWrong: "value:Symbol(s)" },
    { id: "W07", label: "code point counting is a different contract", native: () => "😀".padStart(2, "0"), wrong: () => "0".repeat(Math.max(0, 2 - Array.from("😀").length)) + "😀", expectedNative: "value:\ud83d\ude00", expectedWrong: "value:0\ud83d\ude00" }
  ];
  for (const test of witnesses) {
    const native = capture(test.native);
    const wrong = capture(test.wrong);
    assertEqual(native, test.expectedNative, test.id + " native");
    assertEqual(wrong, test.expectedWrong, test.id + " wrong");
    if (native === wrong) throw new Error(test.id + " witness failed to distinguish");
    console.log("PASS " + test.id + " native=" + JSON.stringify(native) +
      " wrong=" + JSON.stringify(wrong));
  }
  console.log("SUMMARY " + mode + " cases=" + passed + "/40 witnesses=" + witnesses.length + "/7");
}
const requested = process.argv[2] || "both";
if (!["ordinary", "strict", "both"].includes(requested)) throw new Error("unknown context");
console.log("NODE " + process.version);
for (const mode of requested === "both" ? ["ordinary", "strict"] : [requested]) {
  const directive = mode === "strict" ? '"use strict";\n' : "";
  // Re-parse the entire function under each lexical context, not merely its caller.
  Function("mode", "expectedStrict", directive + "return (" + runSuite.toString() +
    ")(mode, expectedStrict);")(mode, mode === "strict");
}

实用原则是先确定业务需要补齐、裁剪、数字格式化还是视觉排版,再选择工具。若只是补齐普通字符串,保留原生行为通常比写一个“万能补零函数”更可靠。

来源核验日期:2026 年 10 月 22 日。转换边界另见 ToString、ToNumber;填充重复与截取规则见 StringPad。以上为独立编写的示例与实测,不是对所有运行时的穷尽验证。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。