Javascript - 对象键->值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5000953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - object key->value
提问by Chameron
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
但我想通过这样的变量
var name = "a";
console.log(obj.name) // but return undefined
How to do this?
这该怎么做?
回答by David Tang
Use []
notation for string representations of properties:
使用[]
符号表示属性的字符串:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
否则,它正在寻找“name”属性,而不是“a”属性。
回答by Longda
obj["a"] is equivalent to obj.a so use obj[name] you get "A"
obj["a"] 等价于 obj.a 所以使用 obj[name] 你会得到 "A"
回答by Longda
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.x
这与obj["x"]
所有有效的 JS 标识符相同,但后一种形式接受所有字符串作为键(不仅仅是有效标识符)。
obj["Hey, this is ... neat?"] = 42
回答by sudheer nunna
https://jsfiddle.net/sudheernunna/tug98nfm/1/
https://jsfiddle.net/sudheerunna/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);
回答by ppaulino
I use the following syntax:
我使用以下语法:
objTest = {"error": true, "message": "test message"};
get error:
得到错误:
console.log(objTest['"error"']);
get message:
获取消息:
console.log(objTest['"messsage"']);
回答by John Murkey
var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);
for (i=0; i<x.length; i++) {
console.log(o[x[i]]);
}
IAB
IAB