1

这是我的代码的简单摘要:

var list = {
    "group":{
        "subgroup1":[{"name1":"Jimmy","name2":"Bob"}],
        "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}]
    }
}
function group(group,name){
    var linktothegroup;

    //Note: In my actual code it will attempt to join a group before creating one this just creates a new one


    //group: Specifies which subgroup to join (my actual code will check if it's valid this is just a simpler version
    //name: the users name

    list["group"][group].push({"name1":name,"name2":""});
    linktothegroup = someway to link that group I just added; //I figured I could find the array slot and specify but that will change if a group is deleted

    this.leavegroup = function(){
        //leaves the group
        //uses the linktothegroup var to be removed from the group
    }
    this.changename = function(name){
        linktothegroup.name1 = name;
        return true;
    }
}
var cubscouts = new group("subgroup1","Billy");
cubscouts.changename("Fred");

我只想能够编辑“subgroupX”字段中的值(基本上用于changename函数),但是总是有组离开和加入,所以我不能在变量中指定数组槽。

所以基本上有没有办法编辑一个变量并改变另一个变量?

4

2 回答 2

2

像这样的东西怎么样?:

var groups = {

  joinGroup: function(groupName, memberName) {
    if(!this[groupName]) {  // create the group if it doesn't exist
      this[groupName] = []  // each group is just an array of names
    }
    var group = this[groupName]
    group.push(memberName)

    // returns an object allowing for the member's name to be changed later
    return {
      // this function becomes a closure, so the group and memberName variables
      // retain their values from the enclosing scope
      changeName: function(newMemberName) {
        group.splice(group.indexOf(memberName), 1, newMemberName)
      }
    }
  }
}

这允许这种用法:

myCubscoutMembership = groups.joinGroup('cubscouts', 'Billy')
myCubscoutMembership.changeName('Bob')

难题的关键部分(如果我正确理解了您的问题)是该changeName函数作为围绕and变量的闭包返回-因此即使稍后调用,也会记住正确的组和旧名称。groupmemberNamechangeName

为了保持答案的重点,我省略了该leaveGroup()方法,但可以将其作为另一个函数添加到返回的对象中。我也没有解决如果删除整个组会发生什么,但这取决于对您的应用程序有意义的内容。

原始样本的一些简化:

  1. list我展平了似乎只包含一个的顶级var group
  2. 我将每个组简化为名称数组而不是哈希,即 ['billy', 'bob']代替{ name1: 'billy', name2: 'bob' }.

希望有些帮助。

于 2013-02-13T19:19:19.953 回答
1

您可以将对象存储在函数中引用的变量中。

function group(group,name){
    //other work here
    var linktothegroup = {"name1":name,"name2":""};
    list["group"][group].push(linktothegroup);

    this.leavegroup = function(){
        var groups = list["group"][group];
        for(var i = 0; i < groups.length; i++) {
            if(groups[i] === linktothegroup) {
                groups.splice(i, 1);
                break;
            }
        }
    }
    this.changename = function(name){
        linktothegroup.name1 = name;
        return true;
    }
}
于 2013-02-13T03:44:31.833 回答