试图在JavaScript的对象属性工作动态 [英] trying to work dynamically with object properties in javascript
问题描述
我想弄清楚,如果这是可行的,但充其量得到语法错误。所以,我想知道,如果它是在所有可能的。
I'm trying to sort out if this is plausible but have gotten syntax errors at best. So I am wondering if it is at all possible.
我已经是一个对象(例如只)
What I have is an object (example only)
var myObj = {
something1_max:50,
something1_enabled:false,
something1_locked:true,
something2_max:100,
something2_enabled:false,
something2_locked:true,
something3_max:10,
something3_enabled:true,
something3_locked:true
}
和我想通过一个函数做的是做这样的事情再次例如总结的事情了。
and what I want to do through a function is do something like again for example to sum things up..
function displayDetails(theScope, obj)
{
console.log(obj.[theScope]_max);
}
(function(){displayDetails('something3', myObj);})()
所以,当 displayDetails()
叫什么范围内我能在这个例子中看到的最大为该范围。在控制台日志的例子我希望看到 10
so when displayDetails()
is called whatever the scope I can see in this example the max for that scope. In the console log for the example I would hope to see 10
推荐答案
JavaScript对象的属性总是可以作为字符串使用进行访问的架的语法,即对象['财产']
。这,当然,这意味着你可以动态地构建字符串:
Properties of JavaScript objects can always be accessed as a string using the bracket syntax, ie object['property']
. This, of course, means you can build that string dynamically:
console.log(obj[theScope + '_max']);
这篇关于试图在JavaScript的对象属性工作动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!