2013-03-13 53 views
1

所以對於PHP我有一組實用的功能做多暗淡陣列的in_array:簡單的JavaScript in_array遞歸函數

function in_array_r($needle, $haystack, $strict = false) { 
    foreach ($haystack as $item) { 
     if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { 
      return true; 
     } 
    } 
    return false; 
} 

但是我試圖重新創建JavaScript的一個類似的,但我似乎無法得到它的工作..這是我所:

function in_array_r(needle, haystack) { 
    var length = haystack.length; 
    for(var i = 0; i < length; i++) { 
     if(haystack[i] == needle){ 
      return true; 
     } 
     if(typeof haystack[i]=='object'){ 
      if(in_array_r(needle, haystack[i])){ 
       return true; 
      } 
     } 
    } 
    return false; 
} 

任何人能發現它爲什麼不工作,我不明白爲什麼它不..

感謝, 約翰

+1

你會得到什麼結果?錯誤訊息?要嘗試的樣本數據以及預期的結果也是有用的。 – 2013-03-13 22:57:34

+0

你有一些測試用例嗎? – Eineki 2013-03-13 23:00:34

+0

啊哈..當鍵不是數字時失敗.. – John 2013-03-13 23:03:03

回答

0

This works .. numeric and non-numeric keys .. doh!

function in_array_r(needle, haystack) { 
    var length = haystack.length; 
    for(var key in haystack) { 
     if(haystack[key] == needle){ 
      return true; 
     } 
     if(typeof haystack[key]=='object'){ 
      if(in_array_r(needle, haystack[key])){ 
       return true; 
      } 
     } 
    } 
    return false; 
}