I have to initialize a collection of objects in constructor and I wanted to support all collection types, such as Arrays, Maps, and Sets. typeof
will only return Object and there doesn't seem to be a generic Collections
utility object that would provide a function like Array.isArray()
.
Coming from Java and classical inheritance styles, my next impulse was to check the object's inheritance. However, my experiments with various prototype functions didn't turn up anything. The best I could figure out was to create a function that checks .prototype.isPrototypeOf(object)
for Map, Set, and Array. But that might be because I don't actually understand Javascripts prototypal inheritance.
Is there a better way to check if an object is a collection?
I have to initialize a collection of objects in constructor and I wanted to support all collection types, such as Arrays, Maps, and Sets. typeof
will only return Object and there doesn't seem to be a generic Collections
utility object that would provide a function like Array.isArray()
.
Coming from Java and classical inheritance styles, my next impulse was to check the object's inheritance. However, my experiments with various prototype functions didn't turn up anything. The best I could figure out was to create a function that checks .prototype.isPrototypeOf(object)
for Map, Set, and Array. But that might be because I don't actually understand Javascripts prototypal inheritance.
Is there a better way to check if an object is a collection?
Share Improve this question asked May 5, 2015 at 19:05 IndoleringIndolering 3,13632 silver badges46 bronze badges2 Answers
Reset to default 5You could check whether it's Iterable
instead:
function isIterable(obj) {
if (obj == null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}
MDN web docs - Iteration protocols
I came up with the following hack, which should be supported by IE 11 and up:
if(typeof collection !== "undefined" && typeof collection.forEach !== "undefined"){
collection.forEach(function(value, param2, collection){
//do stuff
}, this);
}
The param2
is different for each collection type: for Arrays it is the index, for Maps it is the key, and Sets just repeats the same value so as to match the function signature of Maps and Arrays.
The this
argument assigns the anonymous function's this
to the outer function's this
– enabling references to variables assigned in the outer function. Otherwise it will default to the global window
.
I would strongly prefer either a direct test of the object's inheritance or a standards based Collections.isCollection type object and will select a new answer.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744717694a4589719.html
评论列表(0条)