Javascript - object key->value

后端 未结 6 1275
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 17:40
var obj = {
   a: \"A\",
   b: \"B\",
   c: \"C\"
}

console.log(obj.a); // return string : A

but i want to get by through a variable like this

相关标签:
6条回答
  • 2020-12-04 17:40

    Use [] notation for string representations of properties:

    console.log(obj[name]);
    

    Otherwise it's looking for the "name" property, rather than the "a" property.

    0 讨论(0)
  • 2020-12-04 17:49
    var o = { cat : "meow", dog : "woof"};
    var x = Object.keys(o);
    
    for (i=0; i<x.length; i++) {
      console.log(o[x[i]]);
    }
    

    IAB

    0 讨论(0)
  • 2020-12-04 17:50

    https://jsfiddle.net/sudheernunna/tug98nfm/1/

     var days = {};
    days["monday"] = true;
    days["tuesday"] = true;
    days["wednesday"] = false;
    days["thursday"] = true;
    days["friday"] = false;
    days["saturday"] = true;
    days["sunday"] = false;
    var userfalse=0,usertrue=0;
    for(value in days)
    {
       if(days[value]){
       usertrue++;
       }else{
       userfalse++;
       }
        console.log(days[value]);
    }
    alert("false",userfalse);
    alert("true",usertrue);
    
    0 讨论(0)
  • 2020-12-04 17:56

    obj["a"] is equivalent to obj.a so use obj[name] you get "A"

    0 讨论(0)
  • 2020-12-04 17:58

    I use the following syntax:

    objTest = {"error": true, "message": "test message"};
    

    get error:

     var name = "error"
     console.log(objTest[name]);
    

    get message:

     name = "message"
     console.log(objTest[name]);
    
    0 讨论(0)
  • 2020-12-04 18:07

    Use this syntax:

    obj[name]
    

    Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).

    obj["Hey, this is ... neat?"] = 42
    
    0 讨论(0)
提交回复
热议问题