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
508 views
in Technique[技术] by (71.8m points)

jquery - Variable name getting added instead of its value, javascript

I have a problem while adding values to a JavaScript object: the value to add is a key,value pair. Here is sample:

//JavaScript object

var cart=new Object();

function add()
{
  var rating="1"
  var category="somecat";
  var user="user1";

   if(cart[user]==null)

        cart[user]={category:rating};

   else

         cart[user][category]=rating;
 }

What I was expecting is that if user exists in cart object then value for his particular should get replaced, and if user doesn't exist then new user and category should be added.

The code is working fine when user already exists. Problem is, when I am adding a new element with cart[user]={category:rating} then its adding the variable name as key i.e. category , not the value inside it ("somecat").

Is there any way to do this using json, jquery or javascript itself?

Is there any way to assign value inside the variable?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There is no way to use a variable to define a property name inside object literal notation. It accepts identifiers or strings, but both identify property names, not variables.

You have to create the object then add the property:

if(!cart[user]) { 
   cart[user] = {};
}
cart[user][category] = rating;

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

...