admin管理员组

文章数量:1291179

a="12345"
a[2]=3
a[2]='9'
console.log(a) //=> "12345"

What is going on?? This quirk caused me 1 hour painful debugging. How to avoid this in a sensible way?

a="12345"
a[2]=3
a[2]='9'
console.log(a) //=> "12345"

What is going on?? This quirk caused me 1 hour painful debugging. How to avoid this in a sensible way?

Share Improve this question asked Nov 14, 2012 at 0:21 lkahtzlkahtz 4,7968 gold badges48 silver badges74 bronze badges 2
  • 1 same here it took half an hour.... – Gaurav Bhardwaj Commented Apr 4, 2020 at 5:29
  • How could a[2]=3 clarify, whether the behaviour is like expected or not? The oute seems to be the same in both cases. Does it matter that 3 is not a string literal, but '9' is? – Leif Commented Jul 20, 2023 at 14:51
Add a ment  | 

3 Answers 3

Reset to default 8

You cannot use brackets to rewrite individual characters of the string; only 'getter' (i.e. read) access is available. Quoting the doc (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.

That's for "what's going on" part of the question. And for "how to replace" part there's a useful snippet (taken from an answer written long, long ago):

String.prototype.replaceAt = function(index, char) {
    return this.slice(0, index) + char + this.slice(index+char.length);
}

You may use as it is (biting the bullet of extending the JS native object) - or inject this code as a method in some utility object (obviously it should be rewritten a bit, taking the source string as its first param and working with it instead of this).

According to this question, this is not supported among all browsers.

If your strings aren't too long, you can do this relatively easy like that:

var a="12345";
a = a.split("");
a[2]='9';
a = a.join("");
console.log(a);
var letters = a.split('');
letters[2] = 3;
letters[2] = 9;
console.log(letters.join(''));

http://jsfiddle/XWwKz/

Cheers

本文标签: javascript string assignment by index number quirkStack Overflow