Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

javascript - 如何从JavaScript中的变量值创建对象属性? [重复](How to create an object property from a variable value in JavaScript? [duplicate])

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:

(我想向“ myObj”添加一个新属性,将其命名为“ string1”,并为其赋予一个值“ string2”,但是当我这样做时,它返回“ 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?

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

  ask by ecu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...