通过索引号怪癖的javascript字符串分配

标签 javascript

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/

相关文章:

php - 脚本执行时如何获取部分输出?

javascript - 具有相同名称的两个输入

javascript - 输出不显示javascript

javascript - 响应式网页 : SVG visualization?

javascript - 不将图片悬停时停止播放声音

javascript - 使用全屏 API 制作视频全屏

javascript - Angular 中的 ng-repeat 数据绑定(bind)不起作用。我哪里错了?

javascript - v-select 更新 var 而不使用 v-model

javascript - 按顺序迭代 .EACH 循环,其中包含 AJAX 请求

javascript - 使用 React 和 webpack 4 拆分项目; html 标签是意外的标记