Javascript does not get changed array before the click

2

I have a click code:

var layerMap = [];

$(document).on('click', '#TipoMapa', function(){

    console.log(layerMap);

});

And I have a code that changes the layerMap variable:

$(document).on('click', '#tipo', function(){
    layerMap['regional'] = layerMap['regional'] || [];
    layerMap['regional'] = 'Alisson';
});
What happens is that I click the button that creates an array in layerMap and after that, I click on the button to give console.log on the variable layerMap , but the content is always returning me as [] that is, empty. What can it be?

    
asked by anonymous 19.12.2017 / 14:12

2 answers

2

When you try to write a variable in the console, what goes into the console is the result of the call of .toString() in what you passed.

For arrays, the result of .toString() is equivalent to calling .join() , according to the documentation :

  

Implemented in JavaScript 1.8.5 (Firefox 4), and compatible with the 5th version of ECMAScript, the toString () function is generic and can be used on any object. If the object has a join () method, it will be called and that value will be returned.

The important thing to know is that .join() returns Array elements, separated by commas. But you did not put any elements in the Array.

Epa

how come I did not put any elements in the Array?

This syntax:

layerMap['regional'] = layerMap['regional'] || [];

It is object syntax. You added a property to the Array, called "regional", but a property is one thing. One element is another.

So, from two to one:

  • Either you use numeric indexes instead of strings, and then layerMap will behave as you expected ...
  • Or you make layerMap an object instead of Array, and so the properties will appear on the console.

Just do this:

var layerMap = {};
    
19.12.2017 / 14:29
-1

Unfortunately, unlike other languages like PHP, Python, etc ...

Javascript does not accept named key like you did in this example: layerMap ['regional'].

It accepts only numeric keys. If you want named keys, try to work with objects, as arrays will not be your best option to switch.

I would advise looking at w3schools more about Javascript Arrays:

Arrays in javascript

    
19.12.2017 / 14:24