www.webdeveloper.com
Results 1 to 3 of 3

Thread: Searching Two Dimensional Array

  1. #1
    Join Date
    Jun 2009
    Posts
    50

    Searching Two Dimensional Array

    Can anyone tell me why this code would not work? I've found examples using google that are similar, but this code doesn't do either of the branches (true or false). It just poops out. I know that there is data in the array because I can display them sequentially if I want to.

    It's using a two dimensional array and I want to display one of the values.


    Code:

    findValue(array, 'Selection1')


    function findValue(arrayObj, searchFor)
    {

    for (i=0;i<arrayObj.length;i++)
    {
    var found = false
    if (arrayObj[i][0] == searchFor)
    {
    document.write(arrayObj[i][0])
    var found = true
    return true
    break
    }
    else if (((i == (arrayObj.length-1)) && !found)){
    document.write("Not found!")
    return false
    }
    }

    }

  2. #2
    Join Date
    Jun 2009
    Posts
    50
    Well I determined I'm having a problem with something else that's affecting this function.

    What I need is a way to access the individual characters of a string to compare them to another character.

    Such as: if(string[char] = compareTo){
    do this
    }

    However, this syntax doesn't work. Any thoughts?

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,377

    Thumbs up

    Try 'charAt()' of 'indexOf()' functions ...

    Example:
    Code:
    var str = 'abcdefghijklmnopqrstuvwxyz';
    var tmp = '';
    for (var i=0; i<str.length; i++) { tmp += i+': '+str.charAt(i)+'\n'; }
    alert('charAt(i) : returns\n'+tmp);
    
    // Try an invalid input here, like 'A' and you will see a "-1" for the position
    var ch = prompt('Enter a letter (a-z):','a');
    alert(str.indexOf(ch)+' is the position of: '+ch+'\nin the array: '+str);

Thread Information

Users Browsing this Thread

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

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