需要你的帮助,我把这个数组放在"服务器" js文件, 与服务一起存储在allplayers = []; 我想过滤数组,只剩下爵士乐队员(在球员= [];) 使用下面的代码。知道为什么它不起作用?感谢
var players = [
{team: 'bulls', fullName: 'Kerr', position: 'SG', ranking: '7', id: '1' },
{team: 'jazz',fullName: 'stockton', position: 'PG', ranking: '9', id: '2'},
{team: 'jazz',fullName: 'malone', position: 'PF', ranking: '8', id: '3'}
];
export class PlayersComponent implements OnInit {
players = [];
allplayers = [];
bullsPlayers = [];
constructor(private _playerService: PlayerService) {}
filterjazzplayers(){
for (let i = 0; i < this.allplayers.length; i++) {
if (this.allplayers[i].team == 'jazz') {
this.players.push(this.allplayers[i]);
}
}
}
ngOnInit (){
this._playerService.getPlayers()
.subscribe(
allplayers => this.allplayers = allplayers,
error => console.log(<any>error)
);
this.filterjazzplayers();
}
答案 0 :(得分:0)
我可能错了,但我认为在创建具有相同名称的新数组时可能会出现问题。它可能无法分辨本地球员阵列和首发球员阵列之间的区别。以下代码在html文件中作为简单的javascript工作正常。希望这可以帮助您找到遇到问题的地方。
<!DOCTYPE html>
<html>
<script>
var players = [
{team: 'bulls', fullName: 'Kerr', position: 'SG', ranking: '7', id: '1' },
{team: 'jazz',fullName: 'stockton', position: 'PG', ranking: '9', id: '2'},
{team: 'jazz',fullName: 'malone', position: 'PF', ranking: '8', id: '3'}
];
var newPlayers = [];
function filterJazzPlayers()
{
for(let i = 0; i < players.length; i++)
{
if(players[i].team == 'jazz')
{
newPlayers.push(players[i]);
}
}
}
filterJazzPlayers();
for(var j = 0; j < newPlayers.length; j++)
{
console.log(newPlayers[j].fullName);
}
</script>
<html>