Clicking on an object does not work correctly in JavaScript

JavaScript:

var songs = {};
var song = {};
var row = 0;
$('button').on('click', function(){
  row++
  song['name'] = 'hey' + row;
  songs['row' + row] = song;
  console.log(songs);
});

Each time I press the button, it must create a new ['name'] and click it on the "songs" of the object. After 5 clicks, I expected the object to look like this:

{   "row1": {
        "name": "hey1"
    },
    "row2": {
        "name": "hey2"
    },
    "row3": {
        "name": "hey3"
    },
    "row4": {
        "name": "hey4"
    }
    "row5": {
        "name": "hey5"
    }
}

But instead, it looked like

{   "row1": {
        "name": "hey5"
    },
    "row2": {
        "name": "hey5"
    },
    "row3": {
        "name": "hey5"
    },
    "row4": {
        "name": "hey5"
    }
    "row5": {
        "name": "hey5"
    }
}

I think this has something to do with

songs['row' + row] = song;

https://jsfiddle.net/yhk81zbu/3/

Why is this not working and how can I fix it?

+4
source share
2 answers

, row1, row2, row3 .. , song['name'] = 'hey' + row;, "" , , . , song['name'] = 'hey' + row; var song = {'name' : 'hey' + row };, , .

var songs = {}
var row = 0;
$('button').on('click', function(){
  row++
  var song = {'name' : 'hey' + row };
  songs['row' + row] = song;
  console.log(songs);
});
+7

, . , / "name" . - :

var songs = {};
//don't define your object here
var song;
var row = 0;
var songtext;
$('#button').on('click', function(){
  row++;
  songText = 'hey' + row;
  //create a new object each time instead of trying to update the same 'name' property
  //of the global song object
  song = {name: songText};
  songs['row' + row] = song;
  console.log(songs);
});
+1

Source: https://habr.com/ru/post/1624020/


All Articles