创建js对象并给对象属性赋值
发布于 7个月前 作者 Emma0809 659 次浏览

怎样创建类似这样的对象呢? {roomName1: {player1: clientIdOfPlayer1, player2: clientIdOfPlayer2}, roomname2: { player1: clientIdOfPlayer3, player2: clientIdOfPlayer4} 其中roomName、clientIdOfPlayer1、clientIdOfPlayer2都是变量。 求大神指点

3 回复

好独特的需求,如果你是新手的话,静下来想想,你是否真的要这样做。

解决方法:用eval

function create (name, player1, player2) {
    var r = {};
    r[name] = { player1: player1, player2: player2 };
    return r;
}
var obj = {};
obj[roomName1] = {player1: clientIdOfPlayer1, player2: clientIdOfPlayer2};
obj[roomName2] = {player1: clientIdOfPlayer3, player2: clientIdOfPlayer4};
回到顶部