2012-10-28 12 views
7

Voglio fare una funzione che funziona in questo modo:Javascript cercare una matrice per un valore e ottenere la sua chiave

function arraySearch(array, valuetosearchfor) 
{ 
// some code 
} 

se trova il valore della matrice, verrà restituito la chiave, dove ha trovato il valore. Se c'è più di un risultato (più di una chiave) o nessun risultato (niente trovato), la funzione restituirà FALSE.

ho trovato questo codice:

function arraySearch(arr,val) 
     { 
      for (var i=0; i<arr.length; i++) 
       { 
        if (arr[i] == val) 
        {      
         return i; 
        } 
        else 
        { 
         return false; 
        } 
       } 
     } 

e utilizzati in questo modo:

var resultofarraycheck = arraySearch(board, chosen); 
       if (resultofarraycheck === false) 
       { 
         document.getElementById(buttonid).value; 
         chosen = 0; 
       } 

Ma non sembra funzionare. Quando dovrebbe trovare qualcosa, restituisce false invece della chiave (i).

Come posso risolvere questo problema o cosa sto facendo male?

Grazie, e mi dispiace se il mio inglese non era abbastanza chiaro.

+2

Spostare 'false' ritorno a * dopo * il' ciclo for'. (E pensa a gestire il caso con più risultati identici.) – DCoder

+0

[La risposta di Iqbal Djulfri] (http://stackoverflow.com/a/13109873/1233508) è l'unica che soddisfa effettivamente le tue esigenze in merito alle chiavi duplicate. – DCoder

risposta

16
function arraySearch(arr,val) { 
    for (var i=0; i<arr.length; i++) 
     if (arr[i] === val)      
      return i; 
    return false; 
    } 
+0

Grazie mille! Ha funzionato. – shohamh

12

È possibile utilizzare indexOf per ottenere la chiave jsfiddle

if(!Array.prototype.indexOf){ 
    Array.prototype.indexOf = function(val){ 
     var i = this.length; 
     while (i--) { 
      if (this[i] == val) return i; 
     } 
     return -1; 
    } 
} 

    var arr = ['a','b','c','d','e']; 

    var index = arr.indexOf('d'); // return 3 
+1

A meno che non sia necessario supportare IE <9 ... – DCoder

+0

È viceversa, voglio ottenere la chiave dal valore – shohamh

+1

@DCoder Ho aggiunto supprition for IE <9 – Anoop

2
function arraySearch(arr, val) { 
    var index; 
    for (var i = 0; i < arr.length; i++) { 
    // use '===' if you strictly want to find the same type 
    if (arr[i] == val) { 
     if (index == undefined) index = i; 
     // return false if duplicate is found 
     else return false; 
    } 
    } 

    // return false if no element found, or index of the element 
    return index == undefined ? false : index; 
} 

Spero che questo aiuti :)

Problemi correlati