将成员添加到现有对象 [英] Adding members to an existing object
问题描述
假设我们有以下对象:
var obj = {
fn1: function() {
}
}
如何动态添加其他成员,比如说
how can I dynamically add another member to it, say
fn2: function() {}
推荐答案
正如其他人所指出的那样:
As others have pointed out:
obj.fn2 = function(){ ... };
请注意,如果fn2不是有效的标识符,则必须使用数组表示法对象:
Note that if "fn2" is not a valid identifier, you must instead use the 'array' notation for the object:
obj["fn2"] = function(){ ... };
obj["!! crazy-names#allowed?!"] = function(){ ... };
如果你有一个存储在变量中的属性名称,你也可以这样做:
This is also how you would do it if you had the name of the property stored in a variable:
var propName = "fn2";
obj[propName] = function(){ ... };
如果要测试对象是否存在属性,可以使用 in
运算符:
If you want to test if a property exists for an object, you can use the in
operator:
if ("fn2" in obj){ ... }
如果要从对象中删除属性,请使用 delete
keyword:
If you want to remove a property from an object, use the delete
keyword:
var o = { a:42 };
console.log( "a" in o ); // true
delete o.a; // Or delete o["a"]
console.log( "a" in o ); // false
要迭代对象中的所有属性,请使用
for循环中的运算符。请务必 var
该变量使其不是全局变量:
To iterate over all properties in an object, use the in
operator in a for loop. Be sure to var
the variable so that it isn't global:
var o = { a:42, b:17 };
var allPropertyNames = [];
var allPropertyValues = [];
for (var propName in o){
// If you don't do this test, propName might be a property inherited
// by this object, and not a property on the object itself.
if (o.hasOwnProperty(propName)){
allPropertyNames.push(propName);
allPropertyValues.push(o[propName]);
}
}
console.log( allPropertyNames ); // [ "a", "z" ]
console.log( allPropertyValues ); // [ 42, 17 ]
这篇关于将成员添加到现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!