如何根据 Javascript 中变量的内容提取属性?
我试图从名为 data.shake (val1 .. val6 属性)的 jStorage JSON 对象中读出值,但无法找出正确的语法以使其正确运行。例如,控制台日志输出不显示其中存储的值。
var sports = {1:'val1',2:'val2',3:'val3',
4:'val4',5:'val5',6:'val6'};
for (sport in sports) {
if ('data.shake.'+sports[sport] != 0) {
console.log(sports[sport]+':'+'data.shake.'+sports[sport])
//output: val1:data.shake.val1
}
}
I'm trying to read out the values from a jStorage JSON object called data.shake (val1 .. val6 properties), but cant figure the right syntax out so that it runs correctly. for example the console log output doesnt show the value stored in it.
var sports = {1:'val1',2:'val2',3:'val3',
4:'val4',5:'val5',6:'val6'};
for (sport in sports) {
if ('data.shake.'+sports[sport] != 0) {
console.log(sports[sport]+':'+'data.shake.'+sports[sport])
//output: val1:data.shake.val1
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你的意思可能是这样的:
你不能只使用一个字符串(例如
'data.shake.
)并期望Javascript将其转换为你的变量。你正在有效地这样做:显然条件总是会通过,因为非空字符串(
"0"
除外)不等于0
您需要的语法使用 方括号成员运算符,它允许您使用以下结果访问对象的成员一个表达。
I think you probably mean this:
You can't just use a string (e.g.
'data.shake.
and expect Javascript to turn this into a variable for you. You're effectively doing this:Obviously that condition will always pass, because non-empty strings (except
"0"
) are not equal to0
The syntax you need uses the square bracket member operator, which allows you to access an object's members using the result of an expression.
这是我对您尝试使用您提供的代码执行的操作的最佳猜测:
您可以在此处查看它的实际操作:
http: //jsfiddle.net/LseUp/
希望有帮助!
This is my best guess at what you are trying to do with the code you provided:
You can see it in action here:
http://jsfiddle.net/LseUp/
Hope it helps!