下面是我正在处理的简化逻辑,我想在数组中找到匹配位置(文件夹)的文件。
我能够使用vanilla JS循环来实现这一点,你能建议更好/更简单/下划线的方式来实现这样的功能吗?
// source
var arr = [
"file:/anotherName/image1.jpg",
"file:/anotherName/image2.jpg",
"file:/anotherName/image3.jpg",
"file:/folderName/image4.jpg",
"file:/folderName/image1.jpg",
"file:/folderName/image2.jpg",
"file:/folderName/image3.jpg",
"file:/folderName/image4.jpg"
];
// array to store matches
var tmp = [];
for (var i = 0; i < arr.length; i++) {
if( arr[i].indexOf('file:/folderName/') !== -1) tmp.push(arr[i]);
};
console.log(tmp);
// [ 'file:/folderName/image4.jpg',
// 'file:/folderName/image1.jpg',
// 'file:/folderName/image2.jpg',
// 'file:/folderName/image3.jpg',
// 'file:/folderName/image4.jpg' ]
答案 0 :(得分:2)
您可以使用过滤器。我还会使用正则表达式匹配
var arr = [
"file:/anotherName/image1.jpg",
"file:/anotherName/image2.jpg",
"file:/anotherName/image3.jpg",
"file:/folderName/image4.jpg",
"file:/folderName/image1.jpg",
"file:/folderName/image2.jpg",
"file:/folderName/image3.jpg",
"file:/folderName/image4.jpg"
];
var tmp = _.filter(arr, function (el) {
return el.match(/file:\/folderName/);
});
console.log(tmp);