Javascript在运行时扩展对象

Javascript to expand object at runtime?

本文关键字:对象 扩展 运行时 Javascript      更新时间:2023-09-26

这是可能的吗?假设您有以下内容:

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

你能在运行时动态地添加另一个属性吗?

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

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

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代码的字符串的方法。

Simple:

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"

这个"JSON"对象是一个普通的JavaScript对象。你可以这样做:

settings.eyecolor = 'blue';

settings['eyecolor'] = 'blue';

是的,你可以这样编码:

settings.eyecolor = "blue";

var settings = {
  name : 'bilbo',
  age : 63
}
settings.eyecolor = 'blue';

是的,你可以简单地;

settings["eyecolor"] = "blue";

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