Jos*_*osh 0 javascript properties
我有一个存储在$("#budget")中的json变量.data('allocation')
我可以像这样访问它的数据:
id = "5";
alert( $("#budget").data('allocations')[id].amount );
Run Code Online (Sandbox Code Playgroud)
但我需要像这样访问它:
var id = "5";
var field = "amount";
alert( $("#budget").data('allocations')[id].[field] );
Run Code Online (Sandbox Code Playgroud)
使用属性名称中的变量会导致失败.
之后缺少名字.运算符(指[field])
基本上,.xxx
可以替换,["xxx"]
并且组合没有限制.只需使用您用于的相同逻辑id
:
$("#budget").data('allocations')[id][field]
Run Code Online (Sandbox Code Playgroud)
只要密钥在变量中,请替换.key
为[variable]
.所以,obj.key1.key2
变成obj[variable1][variable2]
了相同的逻辑.