admin管理员组文章数量:1391981
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.
本文标签: javascriptCheck if object is collectioniterableStack Overflow
版权声明:本文标题:javascript - Check if object is collectioniterable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744717694a2621504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论