gpt4 book ai didi

javascript - 下划线 - 在数组中搜索匹配的路径

转载 作者:行者123 更新时间:2023-12-02 17:04:14 26 4
gpt4 key购买 nike

下面是我正在处理的简化逻辑,我想在数组中查找具有匹配位置(文件夹)的文件。

我能够使用普通的 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' ]

最佳答案

您可以使用过滤器。我还会使用正则表达式匹配

http://jsfiddle.net/x5j3600z/

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);

关于javascript - 下划线 - 在数组中搜索匹配的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com