Loourr
Loourr

Reputation: 5125

How to get data type from string javascript

I have a few strings

strings = [
    "String",
    "Object",
    "Boolean"
]

and I would like to use them to declare new objects

for(var i = 0; i < strings.length; i++){
    var x = new strings[i];
}

but instead I get this error:

TypeError: string is not a function
  at Object.<anonymous> (/Users/path/code.js)
  at Object.<anonymous> (/Users/path/code.js)
  at Module._compile (module.js:456:26)

How can I treat strings as their underlying types?


Aside:

I know that I could do something like

type_map = {
    String: String,
    Object: Object,
    Boolean: Boolean
}

and then go

for(var i = 0; i < strings.length; i++){
    var x = new type_map[strings[i]];
}

which works, but I'm looking for something slightly more elegant if it exists.

Upvotes: 0

Views: 508

Answers (3)

Loourr
Loourr

Reputation: 5125

Found a great way to do it with the eval function

strings = [
    "String",
    "Object",
    "Boolean"
]

for(var i = 0; i < strings.length; i++){
    var x = new (eval(strings[i]));
}

so to summarize eval("String") === [Function: String]

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

What's wrong with the obvious?

var i, x, constructors = [
    String,
    Object,
    Boolean
];

for(i = 0; i < constructors.length; i++){
    x = new constructors[i];
}

Bear in mind that anything in JS is an object (including "class names") and may be used, pretty much, however you want.

Upvotes: 3

guest
guest

Reputation: 6698

The constructors for these classes are properties of the global object.

For example, in a browser, you could do

console.log(window['String'] === String); // true
var str = new window[strings[0]]();
console.log(str); // ""

Upvotes: 1

Related Questions