3

Does anybody know how to check that a list contain objects or strings?

4
  • 2
    loop on the elements and use typeof. Commented Jul 25, 2013 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. Commented Jul 25, 2013 at 10:20
  • For objects: stackoverflow.com/questions/143847/… Commented Jul 25, 2013 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') Commented Jul 25, 2013 at 10:39

2 Answers 2

2

Iterate over the array and use the condition typeof variable === "string" and typeof variable === "object" to find out.

Sign up to request clarification or add additional context in comments.

1 Comment

avoid == and use === for comparison
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.