Dobre! Go to the point! Is this such a code not working ??

var count = 5; var arr[count] = 'blabla'; 

In PHP, such a focus is quite possible and easy, but what about Javascrypt ???

  • There are no associative arrays in javascript, it uses objects - etki
  • And how to be then (((?? T_t - DanteLoL
  • one
    > And how can I be then, I would even say that the ability to do such things in PHP is rather a disadvantage and a good way to shoot yourself in the leg - DreamChild
  • 3
    > And how to be then (((?? T_t For a start, read the literature on the language before starting to write on it. It helps a general understanding of what you generally do. - fori1ton

2 answers 2

Initialize the variable first explicitly ...

 var count = 5; var arr = []; arr[count] = "blahblah"; 

With objects as associative arrays, also:

 var arr = {} arr["key"] = "value"; 
  • thank you) you are just a foul master) - DanteLoL
  • one
    @DanteLoL do not forget that in a numeric array (the first example) in this way we will create in addition to the 5th element all the previous ones behind it (4.3 ...). - lampa
  • @lampa, this is an interesting question, by the way, are intermediate elements created? In theory, a call to a non-existing element returns undefined both in the array and in the object. The following code is quite admissible: arr = []; arr [5] = "value"; for (i = 0; i <10; i ++) console.log (arr [i]); console.log (arr [100]); That is, no matter which array index is indicated, if an element exists on it, it will return, and if it does not exist, then undefined will return. I think they do not really exist, but the internal functions work with a range from 0 to Array.lenght and therefore capture them too. - Alex Krass

Unlike PHP, in JavaScript it is necessary to declare variables before using them. This is what the var keyword is used for. It allows you to initialize variables, but it is important to understand that assigning values ​​to an array element is not the initialization of an array. Therefore, the correct option:

 var arr = []; arr[count] = 'blabla'; 

PS

What kind of stupid argument " in PHP such a focus is quite possible and easy "? PHP is not JavaScript, it is logical that their syntaxes are different.