For Loop with return不会退出

时间:2016-10-19 21:59:37

标签: javascript for-loop return-value

我有两个数组:

匹配

e

球员

var matches = [
{ playerId: 1, matchId: 1 },

{ playerId: 2, matchId: 1  },

{ playerId: 3, matchId: 2 }];

我想列出与var players= [ { name: "Ronaldo", id: 1 }, { name: "Messi", id: 2 }, { name: "Zlatan" id: 3 }]; 匹配的所有玩家;

matchId 1

如果我只是for (i = 0; i < matches.length; i++) { if (matches[i].matchId == 1) { var p = matches[i].playerId; //alert(p); var currentName = getPlayersInfo(p); alert(currentName); } } function getPlayersInfo(id){ var curID = id; var name; for (i = 0; i < players.length; i++) { if (players[i].id == curID) { name = players[i].name; } } return name; } 而不是我alert(p);,那么我会getPlayersInfo(p)两次alert1,并且可以正常工作但2 getPlayersInfo(p) alert Ronaldoalert,而Messi getPlayersInfo()倍增。

我在const Main = React.createClass({ getInitialState : function() { return { data: null }; }, componentDidMount: function() { axios.get('https://api') .then(function (response) { this.setState({data: response.data}) console.log(response.data); }) .catch(function (error) { console.log(error); }); console.log('mount ' + this.state.data ); }, render() { return ( <h1>{JSON.stringify(this.state.data)}</h1> ) } }) export default Main; 做错了什么?

1 个答案:

答案 0 :(得分:4)

您正在覆盖相同的i变量(这是全局的),因为您没有使用var声明它。在for循环中,使用

for (var i = 0; ...

另一个解决方案是

for (var i = 0, l = matches.length; i < l; i++) {
    var match = matches[i];
    if (match.matchId === 1) {
        var name = players.find(function(player) {
            return player.id === match.playerId;
        });
        alert(name); // note, could be "undefined"
    }
}

如果您必须定期查看其ID,请考虑创建地图(ES2015语法为简洁起见)

let playersById = players.reduce((map, player) => {
    map[player.id] = player;
    return map;
}, Object.create(null));

然后你可以简单地引用

playersById[match.playerId];