我在下面找到了这个代码:
var this.something = {};
var box = {};
box.id = X[0];
box.name = X[1]
box.address = X[2];
if(!this.something.ids[box.id]){
this.something.ids[box.id] = 1;
this.something.datas.push(box);
}
如何更改"this.something"数据结构中具有"box.id"='z'的"box.name"?
有人能帮我吗?
我需要引用"this.something"并编辑关联的"box"数组。但是,我不知道怎么做。
谢谢。
只需进行
for(var i = 0; i < this.something.datas.length; i++){
var box = this.something.datas[i];
if(box.id === 'z'){
box.name = "New Name";
}
}
你可以把它变成的一个函数
var Something = function(){
this.ids = [];
this.datas = [];
this.addBox = function(X){
var box = {};
box.id = X[0];
box.name = X[1]
box.address = X[2];
if(!this.ids[box.id]){
this.ids[box.id] = 1;
this.datas.push(box);
}
}
this.getBoxById = function(id){
for(var i = 0; i < this.datas.length; i++){
var box = this.datas[i];
if(box.id === id){
return box;
}
}
return undefined;
}
}
var something = new Something();
...
var box = something.getBoxById('z');
if(box){
box.name = "new name";
}
首先,不能将属性声明为变量:var this.something = {}
是错误的。请改用this.something = {}
。
什么是X
对象?与其将this.something
作为对象{}
,并将属性作为数组.ids
和.datas
,不如将this.something
用作数组[]
,并简单地将box
对象推送到那里。然后,您可以简单地循环您的数组,并只对要搜索的id元素进行更改。
//Better use array, not object with 2 properties of arrays for ids and objects.
this.something = [];
//Create box object and push to array.
var box = {
id: X[0],
name: X[1],
address: X[2]
}; //You also can create object as you did, but this way is short-hand definition of object with custom properties.
//Push box to array
this.something.push(box)
var boxIdToChange = 'abc';
// Instant edit when you still have access to your 'box' object.
if (box.id === boxIdToChange){
//Make your changes to 'elem' object here.
elem.name = 'New name';
elem.address = 'Different address than original';
}
// If you want to make changes later, for example after creating multiple box elements.
for (var i = 0; i<this.something.length;i++){
var elem = this.something[i];
if (elem.id === boxIdToChange){
//Make your changes to 'elem' object here.
elem.name = 'New name';
elem.address = 'Different address than original';
}
}
如果我明白你的意思,不应该只是:
if (box.id == "z") box.name = "whatever";
是你想要的吗?