如何使用 JavaScript 或 jQuery 更改数组内对象的值? [英] How to change value of object which is inside an array using JavaScript or jQuery?
问题描述
以下代码来自jQuery UI Autocomplete:
The code below comes from jQuery UI Autocomplete:
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
比如我想改变jquery-ui的desc值.我该怎么做?
For example, I want to change the desc value of jquery-ui. How can I do that?
另外,有没有更快的获取数据的方法?我的意思是给对象一个名字来获取它的数据,就像数组中的对象一样?所以它会类似于 jquery-ui.jquery-ui.desc = ....
Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....
推荐答案
你必须在数组中搜索:
function changeDesc( value, desc ) {
for (var i in projects) {
if (projects[i].value == value) {
projects[i].desc = desc;
break; //Stop this loop, we found it!
}
}
}
并像使用它一样
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
更新:
为了更快:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(根据 Frédéric 的评论,您不应该在对象键中使用连字符,或者您应该使用jquery-ui"和 projects[jquery-ui"] 符号.)
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)
这篇关于如何使用 JavaScript 或 jQuery 更改数组内对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!