Javascript在数组中循环搜索字符

Javascript loop through an array searching for characters

本文关键字:搜索 字符 循环 数组 Javascript      更新时间:2023-09-26

我有一个字符串值数组。我想循环遍历数组,并返回任何不仅与字符串值匹配,而且包含这些值的值。解决这一问题的最佳方法是什么?

这是我目前所掌握的,正在寻找确切的价值。

我使用这个逻辑是在几个地方匹配url。对于站点的一部分,getLocation返回/about、/services等。。。还有一个admin部分,返回/adminabout、/adminservices等。

var getLocation = $location.$$path;
var isCustom    = ['about', 'services', 'volunteer', 'contact', 'give', 'blog'];
if(!isCustom.indexOf(getLocation) == -1){ 
  $scope.isCustom = true || false;  
}

使用过滤器获取不包含getLocation值的匹配元素。

var getLocation = $location.$$path.replace('/','');
var isCustom    = ['about', 'services', 'volunteer', 'contact', 'give', 'blog'];
var matchedResult = isCustom.filter(function(value) {
    return value.indexOf(getLocation) < 0
});

由于问题有些不清楚,我假设您正在尝试查找数组项中是否存在字符串。

var getLocation =$location.$$path.replace('/', ''); // assuming it to be admin
var isCustom = ["/adminabout","adminservices","about","services"]

// matches if the string is present in any part of the array item
var matchedResult = isCustom.filter(function(value) {
    return value.indexOf(getLocation) !== -1
});
console.log(matchedResult); //["/adminabout", "adminservices"]

我提出了一个解决方案,可以匹配isCustom值中的值是否包含在getLocation值中。

var searchThroughArray = (function (getLocation) {
var log = [];  
angular.forEach(isCustom, function(item, key) {
      var getLocation = $location.$$path.replace('/', '');
      if(getLocation.contains(item) == true){
        this.push(item);
    }
}, log);
if (0 < log.length){ 
    return true;
};
})();

if(searchThroughArray){
  $scope.isCustom = true; 
}else{
  $scope.isCustom = false; 
};