0

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?

4

3 回答 3

1

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.

于 2013-09-03T03:25:37.673 回答
1

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 :)

于 2013-09-03T03:26:53.417 回答
0
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;
}
于 2013-09-03T03:42:03.733 回答