我的密钥标识符看起来像这样......
const category = key; // could be "bus","car","plane"
对于此示例,请使用"bus"
。我还有一个看起来像这样的字符串数组......
let transportationFields = [
'bus_station', 'bus_stop', 'bus_line', 'took_bus'
'car', 'buyer_of_car', 'car_model',
'train_number', 'train_trip_num', 'train_stop',
];
现在我抓住了
的索引const transFieldValues = transportationFields.indexOf(category) > -1;
但这只会返回true
。我怎样才能抓住它匹配的字段?例如。自category = bus
起。我怎样才能归还所有真实值? ('bus_station', 'bus_stop', 'bus_line', 'took_bus'
)?
提前感谢您的帮助!
答案 0 :(得分:4)
您可以使用.filter()
查找所有匹配项并将其返回到数组中:
let transportationFields = [
'bus_station', 'bus_stop', 'bus_line', 'took_bus',
'car', 'buyer_of_car', 'car_model',
'train_number', 'train_trip_num', 'train_stop',
];
let category = 'bus';
let transFieldValues = transportationFields.filter(function (item) {
return item.indexOf(category) > -1;
});
document.write (JSON.stringify(transFieldValues));

或使用ES6箭头功能:
let transportationFields = [
'bus_station', 'bus_stop', 'bus_line', 'took_bus',
'car', 'buyer_of_car', 'car_model',
'train_number', 'train_trip_num', 'train_stop',
];
let category = 'bus';
let transFieldValues = transportationFields.filter(w => w.indexOf(category) > -1);
document.write (JSON.stringify(transFieldValues));

如果您不介意让Edge用户失去运气,那么您可以使用.includes()
:
let transFieldValues = transportationFields.filter(w => w.includes(category));
...看起来比你> -1
使用的.indexOf()
更好。
答案 1 :(得分:2)
您可以使用Array#filter
let transportationFields = [
'bus_station', 'bus_stop', 'bus_line', 'took_bus',
'car', 'buyer_of_car', 'car_model',
'train_number', 'train_trip_num', 'train_stop',
];
transportationFields = transportationFields.filter(e => {
return e.indexOf('bus') != -1;
});
console.log(transportationFields)

您还可以创建一个函数并将值传递给搜索
let transportationFields = ['bus_station', 'bus_stop', 'bus_line', 'took_bus','car', 'buyer_of_car', 'car_model','train_number', 'train_trip_num', 'train_stop'];
var findField = function(input) {
return transportationFields.filter(e => {return e.indexOf(input) != -1;});
}
console.log(findField('bus'));