简体   繁体   English

在JS中,如何使用字符串定义JS对象参数?

[英]In JS, how can I use a string to define a JS object parameter?

I have a function defined that way: 我有这样定义的函数:

var myObject = new Object();

    function myFunction(someString){

         myObject.someString= 0;

    }

The problem is someString is taken as the string someString instead of the value of that variable. 问题是someString被当作​​字符串someString而不是该变量的值。

So, after I use that function several times over with different someString 's, I would like to get an object with all the values for each someString. 因此,在对不同的someString多次使用该函数之后,我想获得一个包含每个someString的所有值的对象。

But when I loop through that object The only result I get is someString : 0 但是当我遍历该对象时,我得到的唯一结果是someString : 0

I want to get: 我想得到:

John : 0
James : 0
Alex : 0 etc....

How do I do that? 我怎么做? Thanks a lot in advance 提前谢谢

You can use the associative array approach: 您可以使用关联数组方法:

var someString = 'asdf';

myObject[someString] = 0; // {asdf: 0}
myObject['foo'] = 'bar';

You can basically use any string to retrieve your method/parameter. 您基本上可以使用任何字符串来检索您的方法/参数。

var i = 1;
myObject['test' + i] = i + 1; // gives us {test1: 2}

Try this 尝试这个

var myObject = new Object();
    function myFunction(someString){
        myObject[someString]= 0;
    }

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

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