如何在JavaScript中从变量值创建对象属性? [英] How to create an object property from a variable value in JavaScript?

查看:142
本文介绍了如何在JavaScript中从变量值创建对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在'myObj'中添加一个新属性,将其命名为'string1'并赋予它'string2'的值,但是当我这样做时它会返回'undefined:

I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:

var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;

alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'

换句话说:如何创建对象属性并将其赋予存储在变量中的名称,但不是变量本身的名称?

In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?

推荐答案

点表示法和括号表示法

myObj[a] = b;

这篇关于如何在JavaScript中从变量值创建对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆