2013-11-15 78 views
0

我編寫了此代碼示例以瞭解在「名稱」中具有特定值的元素的索引位置。我的可變數據包含這些元素的列表。JavaScript中2個字符串之間的比較不起作用

var data = {"Attributes":[ 
    {"Name":"bedrooms","Value":"4"}, 
    {"Name":"bathrooms","Value":"2"}, 
    {"Name":"property_type","Value":"House"}, 
    {"Name":"rateable_value","Value":"$780,000"}, 
    {"Name":"price","Value":"Price by negotiation"}, 
    {"Name":"location","Value":"13"}, 
    {"Name":"district","Value":"Queenstown-Lakes"}, 
    {"Name":"suburb","Value":"Lower Shotover"}, 
    {"Name":"region","Value":"Otago"}, 
    {"Name":"floor_area","Value":"254m²"}, 
    {"Name":"land_area","Value":"1690m²"}, 
    {"Name":"property_id","Value":"CBM959"}, 
    {"Name":"in_the_area","Value":"playground"}, 
    {"Name":"parking","Value":"Large double garage"} 
]} 

find_index = function(list, str){ 
     list.each(function(index, value){ 
      console.log("Comparing "+value.Name+" with "+str); 
      if(value.Name == str){ 
       return index; 
      } 
     }); 
    }; 

console.log(find_index($(data.Attributes), "bedrooms")) 

當我執行此代碼時,它會在日誌中打印所有的比較,然後返回「undefined」。我期待的是在比較成功時停止迭代,並返回0,這是名稱爲「臥室」的元素的位置。

這裏發生了什麼?我該如何解決它?

+0

您的'return'語句從內部匿名函數返回,而不是'find_index'函數返回。 – Barmar

回答

3

您需要從函數中返回值。

嘗試

find_index = function(list, str){ 
    var idx; 
     list.each(function(index, value){ 
      console.log("Comparing "+value.Name+" with "+str); 
      if(value.Name === str){ 
       idx = index; 
       return false; //Exit out of the loop after the match 
      } 
     }); 
    return idx; 
}; 

.each環路返回值被用作一個布爾值退出或繼續循環。

而且你並不需要創建一個jQuery對象,你可以使用$.each對數組作爲是這樣的:

find_index = function(list, str){ 
     var idx; 
      $.each(list, function(index, value){ 
       if(value.Name === str){ 
        idx = index; 
        return false; //Exit out of the loop after the match 
       } 
      }); 
     return idx; 
    }; 
console.log(find_index(data.Attributes, "bedrooms")); 

您可以INFACT簡化這個好多了,特別是如果你想獲得多場比賽。但是沒有辦法突破地圖,但:

find_index = function(list, str){ 
    return $.map(list, function(val, idx){ 
     if(val.Name === str) return idx; 
    })[0]; //for multiple matches remove 0 
}; 

console.log(find_index(data.Attributes, "district")); 
0

每個函數不會停止(中斷),除非你返回false。你可以有一個變量來分配匹配的索引,然後返回false。

1

Incase,字符串比較失敗嘗試使用localeCompare;這進入營救,準確地匹配字符串。

find_index = function(list, str){ 
var localIndex; 
    list.each(function(index, value){ 
     console.log("Comparing "+value.Name+" with "+str + index); 
     if(str.localeCompare(value.Name) == 0) 
     { 

      localIndex = index; 
      return false; 
     } 

    }); 
    return localIndex; 
}; 

console.log(find_index($(data.Attributes), "bedrooms"));