我得到了一个数组(有关数组中的一个对象,请参见下文)。我想通过一个我将传入的变量访问该对象。你能解释一下为什么变量 whatType 不起作用吗?
const myfunction = (whatType) => {
var mylist = {
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
console.log (mylist.whatType)
}
firstfunction () {
const passthis = 'bio';
myfunction (passthis);
};
你想替换console.log (mylist.whatType)
为console.log (mylist[whatType])
因为
mylist.bio === mylist['bio']
如果bio
是whatType
变量上的字符串,则必须使用:
mylist[whatType]
替换为mylist["bio"]
(与mylist.bio
)
你的功能将是(有更好的名字)
const getUserField = (attr) => {
var user = {
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
}
return user[attr]
}
firstfunction () {
const attr = 'bio';
console.log("User value for " + attr + ":", getUserField (attr))
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句