JSON编码;了解JSON.stringify(s).indexOf(s)?

时间:2018-10-29 04:03:00

标签: javascript json character-encoding

考虑以下功能以确定字符是否为“怪异”。我们将不具有完整性的JSON.stringify字符视为“怪异”:

let isCharWeird = (char) => {
  return JSON.stringify(char).indexOf(char) === -1;
};

我们可以在整个字符范围内调用此函数,以确定哪些字符是“怪异的”,哪些字符不是。如果我们在很大范围的字符(例如,从01,000,000的所有字符代码)中进行调用,则可以跟踪纯奇怪字符的范围以及漂亮的普通字符的范围:

let isCharWeird = (char) => {
  return JSON.stringify(char).indexOf(char) === -1;
};

let weirdRanges = [];
let normalRanges = [];
let weird = true; // Track if the current range is weird/normal
let startInd = 0; // Beginning index of current range
let range = 1000000; // How many chars to try
for (let i = 0; i < range; i++) {
  let nextWeird = isCharWeird(String.fromCharCode(i));
  
  // If the weirdness hasn't changed, skip. Don't skip the final range.
  if (nextWeird === weird && i !== range - 1) continue;
  
  if (i !== startInd)
    (weird ? weirdRanges : normalRanges).push(`: ${startInd} : ${i - 1} (${i - startInd} chars})`);
  
  startInd = i;
  weird = nextWeird;
}

console.log(JSON.stringify({ weirdRanges, normalRanges }, null, 2));

尝试运行该命令,输出结果很有趣!

我的问题是:为什么在代表每批65536个字符的第1个32个字符时JSON似乎没有完整性?

0 个答案:

没有答案