在JavaScript中推送对象无法正常工作(pushing to object not working 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); });每当我点击按钮时,它应该创建一个新的['name']并将其推送到对象'songs'。 点击5次后,我希望对象看起来像这样:
{ "row1": { "name": "hey1" }, "row2": { "name": "hey2" }, "row3": { "name": "hey3" }, "row4": { "name": "hey4" } "row5": { "name": "hey5" } }但它看起来像这样
{ "row1": { "name": "hey5" }, "row2": { "name": "hey5" }, "row3": { "name": "hey5" }, "row4": { "name": "hey5" } "row5": { "name": "hey5" } }我认为这与某些事情有关
songs['row' + row] = song;https://jsfiddle.net/yhk81zbu/3/
为什么这不起作用,我该如何解决?
JavaScript:
var songs = {}; var song = {}; var row = 0; $('button').on('click', function(){ row++ song['name'] = 'hey' + row; songs['row' + row] = song; console.log(songs); });every time i click the button it should create a new ['name'] and push it to the object 'songs'. 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 this
{ "row1": { "name": "hey5" }, "row2": { "name": "hey5" }, "row3": { "name": "hey5" }, "row4": { "name": "hey5" } "row5": { "name": "hey5" } }I think it has something to do with
songs['row' + row] = song;https://jsfiddle.net/yhk81zbu/3/
Why doesn't this work and how can i fix it?
更多推荐
发布评论