0

I was testing giving index as a string to array. But I noticed that array converts string index to number.

for example: A["1"] turns to with A[1]

Can I give a number as a string to array index?

  A["1"] = 1;
  A["3"] = 3;

expected output:

 [ 1: 1, 3: 3 ]

output:

[ <1 empty item>, 1, <1 empty item>, 3 ]

like as usual string index arrays;

  A["a"] = 1;
  A["c"] = 3;

output:

  [ a: 1, c: 3 ]
3
  • Every porperty you set using the bracket notation is coerced to string using String(yourKey) (Except for symbols). So, 1 or "1" will not make any difference. Commented Oct 19, 2019 at 10:15
  • If you explain why you want to do this we can probably offer better suggestions for your data structure. Commented Oct 19, 2019 at 10:18
  • 1
    There's a difference between [ ] (arrays) and { } (objects) Commented Oct 19, 2019 at 10:20

3 Answers 3

1

I think you are confusing objects and arrays.

An array is just a list of items:

const array = [1,2,3,4,5]
// You can access its items by index:
array[0] => 1
array['1'] => 2

An object is a list of key-value pairs and keys are strings:

const obj = { a: 1, b: 2 }
// You can access its item values by key:
array.a => 1
array['b'] => 2
Sign up to request clarification or add additional context in comments.

Comments

0

All property names are strings, So array like numeric property names really aren't any different from any other property names.

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.

A.a = '1' and A['a'] = '1' are equals.

So I think you need to use object. You can do this to get the same output.

 function test() {
  // A["1"] = 1;
  // A["3"] = 3;

  let A = {
    1: 1,
    3: 3
  };

  return A;
}

output

{ '1': 1, '3': 3 }

Comments

0

Everything in JavaScript is an Object.

Array too. It's just has some special properties and notation. An array is an Object where values are stored in key value pair. Keys are index of an array and values are elements. For example:

const a = [1,2,4,6]
Object.keys(a) // iterating through keys will give you indexes [0,1,2,3]

There is just one catch. If you provide index of an array as non negative Integer, it will push value to array else all values will be associated as object.

So

a["a"]=1 // [1,2,4,6, a:1], length of an array will be 4 and key a can be accessed as property

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.