2011-12-14 113 views
0

嗨,这可能吗?说你有以下几点:JavaScript在运行时扩展对象?

var settings = { 
    name : 'bilbo', 
    age : 63 
} 

你可以在运行时动态添加另一个属性,所以它成为?

var settings = { 
    name : 'bilbo', 
    age : 63, 
    eyecolor : 'blue' 
} 
+2

这是一个JavaScript对象,而不是一个JSON对象。你应该看看[MDN - 使用对象](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects)。 – 2011-12-14 14:53:12

+0

它是一个对象文字。没有这样的东西作为JSON对象。 – 2011-12-14 14:54:40

回答

3

只需用点号来添加新的属性:

var settings = { 
    name : 'bilbo', 
    age : 63 
} 

settings.eyecolor = 'blue'; 

// or: settings['eyecolor'] = 'blue'; 
// both of the above will do the same thing: 
// add a property to your object 

console.log(settings); 
/* Logs: 
{ 
    name : 'bilbo', 
    age : 63, 
    eyecolor: 'blue' 
} 
*/ 

附:这是一个常规的JavaScript对象文字。这与JSON无关。

JSON只是一种将对象/数组表示为类似JavaScript代码的字符串的方法。

2

简单:

settings.eyecolor = 'blue'; 

settings['eyecolor'] = 'blue'; 

要么将​​eyecolor字段添加到您的设置在运行时对象。

var settings = { 
    name : 'bilbo', 
    age : 63 
}; 
settings.eyecolor = 'blue'; // can be run anywhere once settings has been defined 
console.log(settings.name, settings.age, settings.eyecolor); // "biblo" 63 "blue" 
1

“JSON”对象是一个普通的JavaScript对象。你可以做到以下几点:

settings.eyecolor = 'blue'; 

settings['eyecolor'] = 'blue'; 
0

是的,你可以简单地;

settings["eyecolor"] = "blue"; 

这会出现在任何重新序列化的字符串中。

0

var settings = { 
    name : 'bilbo', 
    age : 63 
} 

settings.eyecolor = 'blue'; 

这将做到这一点。

1

是的,你可以像这样的代码时:

settings.eyecolor = "blue";