我正在尝试更改我的函数,我可以搜索数组以尝试匹配数组项的任何部分并返回其索引值,此时它必须与整个searchTerm
匹配。
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";
答案 0 :(得分:0)
您只需使用JavaScript .search()
方法。
这将搜索您的字符串,如果找不到相等的子字符串将返回-1。所以你的比较应该是这样的:
if (myArray[i][property].search(searchTerm) !== -1)
return i;
这是JSFiddle来说明:http://jsfiddle.net/vxcjw45d/7/