最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript to expandobject at runtime? - Stack Overflow

programmeradmin3浏览0评论

Hi is this possible? say you have the following:

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

Can you dynamically add another property at runtime so it bees?

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

Hi is this possible? say you have the following:

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

Can you dynamically add another property at runtime so it bees?

var settings = {
  name : 'bilbo',
  age : 63,
  eyecolor : 'blue'
}
Share Improve this question edited Dec 14, 2011 at 14:53 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Dec 14, 2011 at 14:51 MantisimoMantisimo 4,2835 gold badges38 silver badges55 bronze badges 3
  • 2 This is a JavaScript object, not a JSON object. You should have a look at MDN - Working with Objects. – Felix Kling Commented Dec 14, 2011 at 14:53
  • 1 It's an object literal. There is no such thing as a JSON object. – Šime Vidas Commented Dec 14, 2011 at 14:54
  • 1 JSON=javascript object notation. There are no JSON objects, there are only JSON strings which can be parsed into objects. – Jonathan M Commented Dec 14, 2011 at 16:13
Add a ment  | 

6 Answers 6

Reset to default 5

Simply use dot notation to add a new property:

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'
}
*/

P.S. This is a regular JavaScript object literal. It's got nothing to do with JSON.

JSON is simply a means to express an object/array as a string that looks like JavaScript code.

Simple:

settings.eyecolor = 'blue';

or

settings['eyecolor'] = 'blue';

either will add the eyecolor field to your settings object at runtime.

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"

That "JSON" object is a normal JavaScript object. You can do following:

settings.eyecolor = 'blue';

or

settings['eyecolor'] = 'blue';

Yes, you could code it like this:

settings.eyecolor = "blue";

Yes

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

settings.eyecolor = 'blue';

this will do it.

Yes, you can simply;

settings["eyecolor"] = "blue";

This will then appear in any re-serialized string.

发布评论

评论列表(0)

  1. 暂无评论