跳到主要内容

规范控制台格式

接受一个格式字符串(console 的第一个参数)并返回一个规范化的字符串,该字符串的参数数量与 args 完全相同。这样就可以安全地在其前面或后面添加内容。

// Takes a format string (first argument to console) and returns a normalized
// string that has the exact number of arguments as the args. That way it's safe
// to prepend or append to it.
export default function normalizeConsoleFormat(
formatString: string,
args: $ReadOnlyArray<mixed>,
firstArg: number,
): string {
let j = firstArg;
let normalizedString = '';
let last = 0;
for (let i = 0; i < formatString.length - 1; i++) {
if (formatString.charCodeAt(i) !== 37 /* "%" */) {
continue;
}
switch (formatString.charCodeAt(++i)) {
case 79 /* "O" */:
case 99 /* "c" */:
case 100 /* "d" */:
case 102 /* "f" */:
case 105 /* "i" */:
case 111 /* "o" */:
case 115 /* "s" */: {
if (j < args.length) {
// We have a matching argument.
j++;
} else {
// We have more format specifiers than arguments.
// So we need to escape this to print the literal.
// 我们的格式说明符比参数多。所以我们需要转义它以打印字面值。
normalizedString += formatString.slice(last, (last = i)) + '%';
}
}
}
}
normalizedString += formatString.slice(last, formatString.length);
// Pad with extra format specifiers for the rest.
// 用额外的格式说明符填充其余部分。
while (j < args.length) {
if (normalizedString !== '') {
normalizedString += ' ';
}
// Not every environment has the same default.
// This seems to be what Chrome DevTools defaults to.
// 并非每个环境都有相同的默认值。这似乎是 Chrome 开发者工具的默认设置。
normalizedString += typeof args[j] === 'string' ? '%s' : '%o';
j++;
}
return normalizedString;
}