2014-09-18 124 views
1

我想改變我的功能,我可以在那裏搜索數組,嘗試匹配數組項的任何部分並返回它的索引值,此刻它必須匹配整個searchTermJavaScript匹配一個數組的片段並返回索引值

 function arrayObjectIndexOf(myArray, searchTerm, property) { 
      for (var i = 0, len = myArray.length; i < len; i++) { 
       if (myArray[i][property] === searchTerm) return i; 
      } 
      return -1; 
     } 
     $scope.input.icon = "https://mapbuildr.com/assets/img/markers/solid-pin-blue.png"; 
     var look = arrayObjectIndexOf($scope.icons, $scope.input.icon, 'imageSrc'); 

以下是我的圖標示例數組。

 $scope.icons = [ 
      {text: 'Black Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-black.png' }, 
      {text: 'Blue Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png' }, 
      {text: 'Green Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-green.png' }, 
      {text: 'Purple Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-purple.png' }, 
      {text: 'Red Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-red.png' }, 
      {text: 'Yellow Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-yellow.png' }, 
      {text: 'Orange Solid', imageSrc: 'https://mapbuildr.com/assets/img/markers/solid-pin-orange.png' } 
     ]; 

這就是我想在我的$scope.icons陣列,以匹配其將返回索引值

 $scope.pin = "/assets/img/markers/solid-pin-red.png"; 
+1

'如果(!myarray的[I] [屬性] .indexOf(SEARCHTERM)= -1)回報我;' – juvian 2014-09-18 21:28:01

回答

0

你只需要使用JavaScript .search()方法。

這將搜索您的字符串,如果找不到相等的子字符串將返回-1。所以,你的比較應該是這樣的:

if (myArray[i][property].search(searchTerm) !== -1) 
    return i; 

下面是的jsfiddle來說明:http://jsfiddle.net/vxcjw45d/7/

相關問題