我有一個包含檔案路徑資料的嵌套陣列。我試圖做的是獲取嵌套陣列中的每個專案,并首先檢查用戶輸入的檔案名是否存在于嵌套陣列中,如果找到,我想記錄該檔案名的整個路徑。
目前,我已經完成了第一部分,但我無法弄清楚如何安全地從檔案名中獲取檔案路徑。基本上我想要的是在通過檢查嵌套陣列驗證檔案名之后我想記錄檔案路徑,它是具有該檔案名的嵌套陣列中的整個專案。我怎樣才能做到這一點?
我想到的一件事是在驗證檔案名后運行嵌套陣列的回圈并通過拆分每個專案并檢查是否在該路徑中找到檔案名來比較每個專案。但是這種方法對于大型陣列有效嗎?
另外請注意,路徑中的數字是動態的,因此可能會出現多個檔案名相同但標識號不同的專案。
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var currentFileNames = []
var mainDataArrayFilenames = c.forEach((entrys) => {
entrys.forEach((entry) => {
entry.map(function(entry) {
currentFileNames.push(entry.slice(entry.indexOf(':') 1))
});
})
})
function test() {
const input = document.getElementById('input').value
if (currentFileNames.includes(input) == true) {
//expected full path of file name which is input
console.log("path")
} else {
console.log("name not found")
}
}
<input id="input">
<button onclick="test()">click</button>
uj5u.com熱心網友回復:
Array.prototype.forEach不會回傳任何東西。Array.prototype.map如果要將結果存盤在變數中,則必須使用。
您還可以使用Array.prototype.flat.
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var mainDataArray = c
.flat(2) // flatten the array with depth of 3
.map(itm => {
try { // split each entry by :
return itm.split(':');
} catch(e) {
console.error(e);
return []
}
})
.filter(arr => arr.length); // filter all which have no valid information
// this is just for debug purpose and can be removed
mainDataArray.forEach(([path, filename]) => {
console.log(`path "${path}" / filename "${filename}"`)
});
使用上面的部分,您可以在決議后的陣列中進行搜索Array.prototype.filter,并將結果分配給一個串列。
function test() {
const input = document.getElementById('input').value,
list = mainDataArray.filter(([path, filename]) => filename == input);
if (list.length) {
// show all results
console.log(list.map(itm => itm.join(':')).join("\n"));
} else {
console.log("name not found");
}
}
顯示代碼片段
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var mainDataArray = c
.flat(2) // flatten the array with depth of 3
.map(itm => {
try { // split each entry by :
return itm.split(':');
} catch(e) {
console.error(e);
return []
}
})
.filter(arr => arr.length); // filter all which have no valid information
// this is just for debug purpose and can be removed
mainDataArray.forEach(([path, filename]) => {
console.log(`path "${path}" / filename "${filename}"`)
});
function test() {
const input = document.getElementById('input').value,
list = mainDataArray.filter(([path, filename]) => filename == input);
if (list.length) {
// show all results
console.log(list.map(itm => itm.join(':')).join("\n"));
} else {
console.log("name not found");
}
}
<input type="text" id="input">
<input type="button" onclick="test()" value="Search">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363669.html
標籤:javascript 数组
上一篇:如何從元素陣列制作物件陣列
