2

This is related to the arrays in Javascript, which I am trying to use in a complex logic.

Consider the following code:

a['a1'] = 'AJA'

We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).

So, if we go ahead and interpret this:

console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)

It logs :

A
J
A
AJA

Now, all I need is to assign a new character at the 4th position.

When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.

I know that we can do this using string concatenation, i.e. a['a1'] = a['a1'] + 'Y' and get this accomplished.

But why wasn't the first method working? By what other ways can do this?

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 2
    please don't use arrays with custom properties, btw, it is not an array problem, but a string problem. – Nina Scholz Jan 11 '17 at 08:04
  • 1
    If you want to achieve this behaviour you need to declare the string as an array of chars. `var str = "AJA"; --> var strArr = ["A","J","A"];`, when you finish editing the char-array you need to transform it back to the string. – DomeTune Jan 11 '17 at 08:05
  • `var str = "AJA"; var strArr = str.split(''); strArr[3] = "Y"; str = strArr.join('');` –  Jan 11 '17 at 08:23
  • @LearnHowToBeTransparent This could have worked for a simple array. But not here.. –  Jan 11 '17 at 08:27

2 Answers2

3

Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.

You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.

let a  = {};
a['a1'] = 'AJA';

a.a1[1] = 'A';

console.log(a.a1);

For more you can see MDN Documentation

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
-2

As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:

var s = 'ss';

When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)

  • There’s no assignment to the string itself, only to a property (not `s = …` but `s[2] = …`). How does this relate to the question? – Sebastian Simon Jan 11 '17 at 08:33
  • Just an example, when you try to evaluate a[a1][3] or a.a1[3] you'll get the same type as the example I referred above. try typeof(a[a1][3]) – yupengzhang Jan 11 '17 at 08:41