目前我正在循环播放一系列歌手,并且在歌手阵列中有一个名为歌曲的对象,每个歌手都会唱歌。我有for循环设置,所以我将返回所有的歌手,但我无法循环并返回每个歌手的歌曲。
这是我想要返回的演示数据:
singers:{
1{id:1, name: john, songs:[{id:#, name: song1}, {id:#, name:song2}]}
2{id:2, name: jack, songs:[{id:#, name: song1}, {id:#, name: song2}, {id:#, name: song3}]}
}
这就是我所拥有的,所以我可以循环获取歌手名单,但我还要为每位歌手返回一份歌曲列表:
var singer, singerData=[];
for (singer in singers) {
if (singers.hasOwnProperty(singer)) {
singerData.push(new viewModel(singers[singer]));
}
}
viewModel = function(singer){
var self;
self.singerName = ko.observable(singer.singerName);
.....
}
如何循环返回每个歌手的歌曲列表,以便我可以按如下方式显示数据:
John: song1, song2
Jack: song1, song2, song3
答案 0 :(得分:0)
当for(singer in singers)
singer
指的是您要枚举的对象中的索引或键时,而不是值。你需要做singers[singer]
。同时执行var singer
以避免污染全局范围:
for (var i in singers) {
var singer = singers[i];
if (singer.hasOwnProperty('songs')) {
singerData.push(new viewModel(singer));
}
}
也来自你的问题:
在歌手阵列中有一个名为歌曲的对象 歌手唱了
我假设你的意思是你有一个像这样的对象数组?
var singers = [
{ songs: ['song name', 'other song'] }
];
答案 1 :(得分:0)
试试这个
var result = [];
singers = [{id:1, name: "john", songs:[{id:"#", name: "song1"},{id:"#", name:"song2"}]},{id:2, name: "jack", songs:[{id:"#", name: "song1"}, {id:"#", name: "song2"}, {id:"#", name: "song3"}]}];
for( i in singers ) {
singer = singers[ i ];
var songs = [];
for( j in singer.songs ) {
song = singer.songs[ j ];
songs.push( song.name );
}
result.push( singer.name + ": " + songs.join( ", ") );
}
result = result.join( "\n" );
alert( result );