Does anybody know how to check that a list contain objects or strings?
Asked
Active
Viewed 1,215 times
3
-
2loop on the elements and use typeof. – dievardump Jul 25 '13 at 10:17
-
@dievardump, I have tired with looping and checking the item whether that is 'object' or 'string'. But I want to check without looping through the list. – NkS Jul 25 '13 at 10:20
-
For objects: http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array – jrd1 Jul 25 '13 at 10:22
-
@NkS if you are sure the list will always contain the same type, so you can juste typeof the first element in the list. Else you will have to iterate. But you can have a clever iteration. One which will stop as soon as there is more than one type (and return something like `'mixed'`) – dievardump Jul 25 '13 at 10:39
2 Answers
2
Iterate over the array and use the condition typeof variable === "string"
and typeof variable === "object"
to find out.

mohkhan
- 11,925
- 2
- 24
- 27
1
In Javascript all arrays are untyped, meaning: nothing will take care of what is in it, if you don't do it yourself.
Since array is a composite structure addressed by an integer value, you can check every address for the exact type stored inside. If this is an array created by someone else. However, what is your array type if you find objects, strings and int's in it?
Other options:
- create your own structure where you specify type on its creation and throw error in
add(item)
method if the items type is violated - create your own structure where in
add(item)
you take care of the type and write it in some property of that structure

OzrenTkalcecKrznaric
- 5,535
- 4
- 34
- 57