简体   繁体   中英

Dynamically create Javascript Object from String and put object as parameters of function

I would like to create Javascript object from Javascript String.

var arrayOfName = new Array();
arrayOfName.push("module1");
arrayOfName.push("module2");
arrayOfName.push("module3");
arrayOfName.push("module4");

For this example, i would like to create 4 objects : module1, module2, module3 and module4.

And after, how can i passed these object as a parameters of a function ? like this :

this.myFunctionTest = function myFunctionTest(module1, module2, module3, module4) {
  // ...
}

Ideally, the code must work for all elements which are in the Javascript Array called "arrayOfName".

You can use Function.prototype.apply like this

myFunctionTest.apply(this, arrayOfName);

The apply function passes all the elements of arrayOfName as parameters to myFunctionTest .

As the number of parameters grow in number, you may not want to or find it difficult to maintain the number or parameters. Don't worry, JavaScript has got that covered :) It has something called arguments which is an array like object. You can access the first parameter with arguments[0] , like accessing a normal array object.

var arrayOfName = [];
arrayOfName.push("module1");
arrayOfName.push("module2");
arrayOfName.push("module3");
arrayOfName.push("module4");

function myFunctionTest(param1, param2, param3) {
    console.log(param1, param2, param3);
    console.log(arguments);
}

myFunctionTest.apply(this, arrayOfName);
// module1 module2 module3
// { '0': 'module1', '1': 'module2', '2': 'module3', '3': 'module4' }

If you want to require node modules, with this method

var modules = ["lodash", "underscore", "q"];
require.apply(this, modules);

But if you want to get the objects returned by the require for each of the modules, then your best bet would be using Array.prototype.map with require , like this

console.log(modules.map(require));

If you have a function like this

function modules(module1, module2, ...) {
    ...
}

And if you want to invoke it with all the loaded modules, then you would do something like this

modules.apply(this, modules.map(require));

Using .apply function of Function prototype

myFunctionTest.apply(this, arrayOfName);

Note: You can find more here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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