Variable name getting added instead of its value, javascript

前端 未结 3 1330
余生分开走
余生分开走 2020-12-12 05:27

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         


        
3条回答
  •  我在风中等你
    2020-12-12 06:15

    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;
    

提交回复
热议问题