www.webdeveloper.com
Results 1 to 2 of 2

Thread: check if x is an item of an array

Hybrid View

  1. #1
    Join Date
    Oct 2012
    Posts
    3

    Question check if x is an item of an array

    hi

    Code:
    <script type=text/javascript>
    
    var dd=[1,3,4,6,8.2,"w",7,"d","q"]
    var df=["a","d","f","g","h","w","q"]
    
    for (i=0;i<10;i++){
    if (dd[i] in df) {
    document.write(dd[i]+ " " +i);
    
    }
    }
    
    </script>
    if (dd[i] in df) :

    if dd[i] == any element in df ...do something

    any suggestions are welcomed.

    thanks

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    743
    Try using the indexOf() method for arrays. This will let you run the same loop and simply check if the value exists in the array or not. The indexOf() function will return the location of the item in that array if it's found, otherwise it returns a -1.

    Code:
    <script type=text/javascript>
    var dd = [1,3,4,6,8.2,"w",7,"d","q"];
    var df = ["a","d","f","g","h","w","q"];
    
    for(i = 0 ; i < 10 ; i++) {
      if(df.indexOf(dd[i]) >= 0) {
        document.write(dd[i] + " " + i + "<br>");
      }
    }
    </script>
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles