javascript搜索数组,返回找到的密钥

时间:2016-05-03 17:51:57

标签: javascript jquery arrays

我正在尝试在数组中搜索值并返回找到的值的值。

示例:

var arr=['Volvo460', 'Fiat500', 'fiat400', 'volvo C7', 'Saab 95'];
var search = 'volvo';

预期结果:

returned_array = ['Volvo460','volvo C7'];

任何?

编辑 - 符合数组; - )

6 个答案:

答案 0 :(得分:3)

希望这个答案:

var arr=['Volvo460', 'Fiat500', 'fiat400', 'volvo C7', 'Saab 95'];
var search = 'volvo';

var returned_array =arr.filter(function(itm,i,a){
  if(itm.toLowerCase().indexOf(search) > -1)
    return i==a.indexOf(itm);
});

alert(returned_array);

这是一个有效的example

答案 1 :(得分:2)

您可以使用 filter() 过滤数组中的值

var arr = [
  'Volvo460',
  'Fiat500',
  'fiat400',
  'volvo C7',
  'Saab 95'
];
var search = 'volvo';

var res = arr.filter(function(v) {
  // convert both string to lower to make it case insensitive
  return v.toLowerCase().indexOf(search.toLowerCase()) > -1;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>')

答案 2 :(得分:1)

&#13;
&#13;
var arr = [
   'Volvo460',
   'Fiat500',
   'fiat400',
   'volvo C7',
   'Saab 95'
];
var search = 'volvo',

arr.map(function(v) {
  if(v.toLowerCase().indexOf(search.toLowerCase()) > -1) return v;
});
&#13;
&#13;
&#13;

答案 3 :(得分:1)

试试这个:

var obj = {
  1: 'Volvo460',
  2: 'Fiat500',
  3: 'Fiat400',
  4: 'volvo C7',
  5: 'Saab 95'
};
var search = 'volvo'
for (key in obj) {  
    if (obj[key].toLowerCase().search(search) == 0)
        console.log('found:' + key + '=' + obj[key])
}

键也可以是字符串:

var obj = {
  'a': 'Volvo460',
  'b': 'Fiat500',
  'c': 'Fiat400',
  'd': 'volvo C7',
  'e': 'Saab 95'
};
var search = 'volvo'
for (key in obj) {  
    if (obj[key].toLowerCase().search(search) == 0)
        console.log('found:' + key + '=' + obj[key])
}

如果你需要一次添加一个键,你可以这样做:

var obj = {};
obj['a'] = 'Volvo460';
obj['b'] = 'Fiat500',
obj['c'] = 'Fiat400',
obj['d'] = 'volvo C7',
obj['e'] = 'Saab 95'

var search = 'volvo'
for (key in obj){   
    if (obj[key].toLowerCase().search(search) == 0)
        console.log('found:' + key + '=' + obj[key])
}

这里的工作示例:https://jsfiddle.net/Lfpk6zgo/5/

答案 4 :(得分:1)

带有正则表达式的提案

var arr = ['Volvo460', 'Fiat500', 'fiat400', 'volvo C7', 'Saab 95'];
    search = RegExp('volvo', 'i'),
    result = arr.filter(search.test.bind(search));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 5 :(得分:1)

var arr = ["volvoCar", "123volvo", "BMW", "VW", "etc"],
new_array = [];

for(var i = 0;i<arr.length;i++){
    if(arr[i].match(/volvo/ig)){
      new_array.push(arr[i]);
   }

}
console.log(new_array);