a="12345"
a[2]=3
a[2]='9'
console.log(a) //=> "12345"
这是怎么回事??这个怪癖让我痛苦地调试了 1 个小时。如何以明智的方式避免这种情况?
最佳答案
您不能使用方括号重写字符串中的单个字符;只有“getter”(即读取)访问可用。引用文档(MDN):
For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.
那是问题的“发生了什么”部分。对于“如何替换”部分,有一个有用的片段(摘自 an answer written long, long ago ):
String.prototype.replaceAt = function(index, char) {
return this.slice(0, index) + char + this.slice(index+char.length);
}
您可以按原样使用(硬着头皮扩展 JS native 对象)- 或将此代码作为方法注入(inject)到某些实用程序对象中(显然应该稍微重写一下,将源字符串作为其第一个参数和使用它而不是 this
)。
关于通过索引号怪癖的javascript字符串分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13371206/