简体   繁体   English

如何使用变量或函数名称作为JavaScript中对象属性的占位符?

[英]How to use a variable or a function name to be a place holder for a object's properties in JavaScript?

Is there any easy way in JavaScript to use a variable or a function name as a property of a object like this: 在JavaScript中有任何简单的方法可以使用变量或函数名作为对象的属性,如下所示:

 var someObject = { piece1: 'one', piece2: 'two' }; var trial = "piece1"; alert(someObject[trial]); function someFunction(secondTrial) { return someObject[secondTrail]; }; alert(someFunction(piece1)); 

so that "trial" & "secondTrial" will work as well as "someObjects"'s property; 这样“试验”和“第二部分”就会起到“某些对象”的作用; so essentially they would both work like "someObject.piece1"? 所以基本上他们都会像“someObject.piece1”一样工作?

When you do someFunction(piece1) , piece1 will be treated as a variable and since it is not defined yet, ReferenceError: piece1 is not defined will be thrown. 当你执行someFunction(piece1)piece1将被视为一个变量,因为它尚未定义, ReferenceError: piece1 is not defined将抛出ReferenceError: piece1 is not defined You need to pass that as a string, like this 您需要将其作为字符串传递,如下所示

alert(someFunction("piece1"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM