变量名称被添加而不是它的值,javascript [英] Variable name getting added instead of its value, javascript
问题描述
向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;
}
我期待的是,如果 user
存在于购物车对象中,然后其特定值将被替换,如果 user
不存在,则应添加新用户和类别。
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.
当用户
已经存在时,代码工作正常。问题是,当我用 cart [user] = {category:rating}
添加新元素时,它将变量名添加为键即类别,而不是其中的值(somecat)。
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").
有没有办法用json,jquery或javascript本身做这个?
Is there any way to do this using json, jquery or javascript itself?
有没有办法在变量中赋值?
Is there any way to assign value inside the variable?
推荐答案
无法使用变量来定义属性名称内部对象文字符号。它接受标识符或字符串,但都标识属性名称,而不是变量。
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;
这篇关于变量名称被添加而不是它的值,javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!