编辑javascript数组而不重新加载页面

时间:2010-09-07 11:48:03

标签: javascript arrays

我有一个在页面加载时加载的文字数组......见下文:

<script type="text/javascript">
var members = [
    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },
    {
       name:"Ben Sinclair",
       id:"ed34b5a4-9b2f-102c-8475-9e610b13400a",
       conflict:"true",
       positions:[
          {
             id:"f00c2128-8895-102d-80ee-95364de284f0"
          },
          {
             id:"f00c68ea-8895-102d-80ee-95364de284f0"
          },
          {
             id:"4cde6824-8897-102d-80ee-95364de284f0"
          },
          {
             id:"4cde9ea2-8897-102d-80ee-95364de284f0"
          }
       ],
       locations:[
          {
             id:"88fb5f94-aaa6-102c-a4fa-1f05bca0eec6"
          },
          {
             id:"930555b0-a251-102c-a245-1559817ce81a"
          }
       ]
    },
    {
       name:"Debbie Wright",
       id:"fa49307a-9cfb-102d-bd08-842c500d506d"
    }
]
</script>

无论如何编辑数组而不重新加载页面?例如,我想将conflict:"true"添加到Alan Lim ...

例如:

改变这个:

    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },

对此:

    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       conflict:"true",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },

信任是有意义的:)原因是因为我使用其他JavaScript从这个数组中提取信息。当我使用其他JavaScript进行更改时,我想添加和减去此数组以反映更改...

2 个答案:

答案 0 :(得分:6)

你可以循环查找你想要的成员(按照名称似乎给出了问题)然后编辑它,如下所示:

for(var i=0; i<members.length; i++) {
  if(members[i].name == "Alan Lim")
    members[i].conflict = "true";
}

You can give it a try here,或者像this那样使它更通用:

function setProp(name, prop, value) {
  for(var i=0; i<members.length; i++) {
    if(members[i].name == name)
       members[i][prop] = value;
  }
}

答案 1 :(得分:3)

由于你的数组是用数字索引的,你能不能这样做:

members[0]['conflict'] = "true";