Javascript 在运行时扩展对象?

Man*_*imo 1 javascript

嗨,这可能吗?说你有以下几点:

var settings = {
  name : 'bilbo',
  age : 63
}
Run Code Online (Sandbox Code Playgroud)

您可以在运行时动态添加另一个属性使其变为吗?

var settings = {
  name : 'bilbo',
  age : 63,
  eyecolor : 'blue'
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ber 5

只需使用点表示法添加新属性:

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'
}
*/
Run Code Online (Sandbox Code Playgroud)

PS 这是一个常规的 JavaScript 对象字面量。它与 JSON 无关。

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