我有一个 JS 示例,其中我正在使用原始类型。我首先尝试理解 Javascript 何时将原语转换为对象,但后来转向用其他函数替换一些原型(prototype)函数。在我的示例中,您可以看到我将 charAt 函数替换为 Join。我期望它只是将数组连接到一个字符串中并将其返回给我。相反,它会在输出中添加 1。如果 1 与每个字符的数组索引相对应,如果它们在那里(a0l1e2r3t4(516)7),那就有意义,但它会产生:a1l1e1r1t1(111),这是我没想到的。多余的1从哪里来?
String.prototype.getVal= function() {
return this;
}
var a = "alert(1)";
var b = a.getVal();
console.log(a); //"alert(1)"
console.log(typeof a); //"string" (still a primitive)
console.log(b); //"String {0: "a", 1: "l", 2: "e", 3: "r", 4: "t", 5: "(", 6: "1", 7: ")", length: 8, [[PrimitiveValue]]: "alert(1)"}"
console.log(typeof b); //"object"
a.constructor.prototype.charAt = [].join;
console.log("CharAt using Join:", b.charAt(1));//a1l1e1r1t1(111)?
最佳答案
JavaScript join 方法采用一个参数,即分隔符。由于您传入了 1
,它会使用该分隔符连接字符串 alert(1)
的所有字符。
a + 1
l + 1
e + 1
r + 1
t + 1
( + 1
1 + 1
)
我们预计 1
总共出现八次,根据您的输出,这是正确的。
引用号:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
为了获得更好的视觉效果,请使用逗号或空格调用新的 charAt
。
关于javascript - 用 join 替换 charAt 会导致奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38193565/