我有一个像这样的JSON数组:
_htaItems = [
{"ID":1,
"parentColumnSortID":"0",
"description":"Precondition",
"columnSortID":"1",
"itemType":0},
{"ID":2,
"parentColumnSortID":"0",
"description":"Precondition",
"columnSortID":"1",
"itemType":0}]
Run Code Online (Sandbox Code Playgroud)
我想通过将ID,列名和新值传递给函数来更新它:
function updateJSON(ID, columnName, newValue)
{
var i = 0;
for (i = 0; i < _htaItems.length; i++)
{
if (_htaItems[i].ID == ID)
{
?????
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何更新价值?我知道我可以做以下事情:
_htaItems[x].description = 'New Value'
Run Code Online (Sandbox Code Playgroud)
但在我的原因中,列名称作为字符串传递.
T.J*_*der 25
在JavaScript中,您可以使用文字表示法访问对象属性:
the.answer = 42;
Run Code Online (Sandbox Code Playgroud)
或者使用字符串作为属性名称的括号表示法:
the["answer"] = 42;
Run Code Online (Sandbox Code Playgroud)
这两个语句完全相同,但在第二个语句的情况下,由于括号中的内容是一个字符串,它可以是任何解析为字符串的表达式(或者可以强制转换为一个字符串).所以这些都做同样的事情:
x = "answer";
the[x] = 42;
x = "ans";
y = "wer";
the[x + y] = 42;
function foo() {
return "answer";
}
the[foo()] = 42;
Run Code Online (Sandbox Code Playgroud)
......这是设置answer对象的属性the来42.
因此,如果description在您的示例中不能是文字,因为它是从其他地方传递给您的,您可以使用括号表示法:
s = "description";
_htaItems[x][s] = 'New Value';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18890 次 |
| 最近记录: |