jQuery{}数组如何引用/编辑/更新/删除等
考虑以下几点:jQuery{}数组如何引用/编辑/更新/删除等,jquery,arrays,edit,Jquery,Arrays,Edit,考虑以下几点: var service_call_array = { 3 : 'test', 4 : 'more of a test eh?', 5 : 'more info required' }; 我可以这样循环 $(function() { $.each(service_call_array, function(key, value) { alert(key + ':' +value); } }); 但是,原则上,我将
var service_call_array = {
3 : 'test',
4 : 'more of a test eh?',
5 : 'more info required'
};
我可以这样循环
$(function() {
$.each(service_call_array, function(key, value) {
alert(key + ':' +value);
}
});
但是,原则上,我将如何添加第四项key:value,如何通过key(比如key:4)更新、编辑或更改值,如何通过引用key删除,以及如何通过key引用元素值而不循环
提前感谢首先,如果要使用数字进行索引,请不要使用对象{},而是使用数组[] 其次,您可以添加如下新项目:
var obj = {};
obj.newItem = 'newItem'; // You can use the dot syntax when your member
// name is a valid identifier.
obj['new Item 2'] = 'newItem2'; // Or, you can use the bracket notation if it
// isn't.
var arr = [];
arr[0] = 'firstItem'; // Use the bracket syntax.
arr[42] = 'anotherItem'; // The indices don't have to be contiguous.
要访问或更新值,可以使用类似的语法。所有值都是动态的,因此无论您是第一次添加还是更新,它们在语法上都是相同的:
var a = obj.newItem; // Access with dot syntax
var b = obj['new Item 2']; // Access with bracket syntax
obj.newItem = 'updatedValue' // Update with new value using dot syntax
obj['new Item 2'] = 42 // Update with new value using bracket syntax
// Note that the type of the value doesn't have
// to remain the same.
要实际删除一个值,请使用delete
关键字:
delete obj.newItem; // Now, obj.newItem is undefined again.
您可以通过调用
service\u call\u array.key
获得一个引用,然后您可以对其进行更新或执行任何操作
添加:
service_call_array.key = 'newValue';
service_call_array[key] = 'newValue';
删除:
delete service_call_array.key;
delete service_call_array[key];
首先,这是一个对象,而不是数组。数组只能具有数字索引和特殊语义,如
.length
属性。现在,回答你的问题
这里有一个普通的老JavaScript对象,您正在为其分配属性。以下是总结:
访问属性
使用o.key
或o[“key”]
语法,例如:
var object = {
foo: "bar"
};
alert(object.foo); // displays "bar"
var translate = {
"hello": "bonjour",
"goodbye": "au revoir"
};
var word = "hello"; // received through some kind of user input
alert(translate[word]); // displays "bonjour"
将对象用作查找表时,o[“key”]
语法特别方便,例如:
var object = {
foo: "bar"
};
alert(object.foo); // displays "bar"
var translate = {
"hello": "bonjour",
"goodbye": "au revoir"
};
var word = "hello"; // received through some kind of user input
alert(translate[word]); // displays "bonjour"
设置属性
与访问属性类似,但现在将它们放置在赋值的左侧。属性是否已经存在并不重要,必要时将创建它
var object = {};
object.foo = "bar";
alert(object.foo); // still "bar"
删除属性
使用delete
语句
var object = {
foo: "bar"
}
alert(object.foo); // displays "bar"
delete object.foo;
alert(object.foo); // displays "undefined"
alert(object.foo === undefined); // displays true
这些数字是不相关的,很抱歉混淆了假设一个键是文本字符串谢谢我只是想澄清正确的机制和符号。