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

How to create javascript object with custom name? - Stack Overflow

programmeradmin6浏览0评论

It's a little bit difficult to explain what I need, so I'll use some non-working code:

function createSimpleObjet(name, value){
    return {
        name: value
    };
}

//create it
var obj = createSimpleObject('Message', 'Hello World!');
//test it:
alert(ojb.Message); //should alert 'Hello World!'

How would I go about?

It's a little bit difficult to explain what I need, so I'll use some non-working code:

function createSimpleObjet(name, value){
    return {
        name: value
    };
}

//create it
var obj = createSimpleObject('Message', 'Hello World!');
//test it:
alert(ojb.Message); //should alert 'Hello World!'

How would I go about?

Share Improve this question asked May 21, 2012 at 9:41 Kees C. BakkerKees C. Bakker 33.4k31 gold badges118 silver badges207 bronze badges 3
  • 1 possible duplicate of create object using variables for property name – Felix Kling Commented May 21, 2012 at 10:01
  • See also Using constants as indices for JavaScript associative arrays. – Asherah Commented May 21, 2012 at 10:15
  • Yeah, I see. Really difficult to search where you are looking when one doens't know how do call it :D – Kees C. Bakker Commented May 21, 2012 at 10:29
Add a comment  | 

2 Answers 2

Reset to default 13

In order to do this try square bracket notation:

function createSimpleObject(name, value){
    var obj = {};
    obj[name] = value;
    return obj;
}

You can't use a variable as a property name in an object literal. You have to create the object, and then assign the value using square bracket notation.

var object = {};
object[name] = value;
发布评论

评论列表(0)

  1. 暂无评论