Question

I have an array holding misc. content, and I need to somehow produce a new array that will hold types of data at coresponding index, i've tried using:

typeof ( ["my", "misc", new Data] ), 

but it gives me not what I'm expecting... Is there a way to generate such array?

Was it helpful?

Solution

This can be achieved using the map function.

var types = ["my", "misc", new Data].map(function (item) {
    return typeof item;
});

However, I think this might be what you're looking for:

var types = ["my", "misc", new Data].map(function (item) {
    var name = item.constructor && item.constructor.name;
    return name? name: typeof item;
});

Please note that Function.name is not standard and depending on the way you declared your functions, there might not be any reliable way to find the function's name.

OTHER TIPS

Your code doesn't work because typeof doesn't work in an array context, it will just return the type of your array, which is object.

The cross-browser solution is to build a new array with the type of each corresponding element of your original array:

var arr = ["my", "misc", new Data()];

var types = [];
for (var i = 0; i < arr.length; ++i) {
    types.push(typeof(arr[i]));
}

Alternatively, you may use Array.map() to accomplish the same using a one-liner :)

function type( o ) {
    var out = typeof o;
    (
     (
      out =
        ( o && o.constructor === window.constructor ) && 'window'
        || ( ( Object.prototype.toString.call( o ) ).match( /\b(\w+)\]$/ ) )[1].toLowerCase()
     ) === 'number'
    )
    && ( isNaN( o ) && ( out = 'NaN' ) );
    return out;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top