假设我有一个看起来像这样的json:
let jsonExample = {
"name": "foo",
"age": 43,
"number" : 13,
"id": "osaid9r"
}
我的目标是创建一个JavaScript函数getField(json, fieldName)
,该函数将接收json和代表字段名称的字符串,并返回由fieldName
表示的值。
getField(jsonExample, "name") = "foo"
getField(jsonExample, "number") = 13
如何编写这样的功能?
答案 0 :(得分:3)
您可以这样写:
let jsonExample = {
"name": "foo",
"age": 43,
"number" : 13,
"id": "osaid9r"
}
function getField(obj, field){ return obj[field];}
console.log(getField(jsonExample,"name"));
console.log(getField(jsonExample,"number"));
答案 1 :(得分:1)
let jsonExample = {"name": "foo","age": 43,"number" : 13,"id": "osaid9r"}
function getField(json, key)
{
return json[key];
}
console.log(getField(jsonExample,"number"));