在JavaScript中推送对象无法正常工作(pushing to object not working correctly in JavaScript)

编程入门 行业动态 更新时间:2024-10-24 06:33:27
在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?

更多推荐

本文发布于:2023-08-07 01:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   对象   工作   JavaScript   correctly

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!