我被困在這段代碼上。我有一個帶有兩個選項卡的示例表。第一個選項卡是新專案。一個新專案由兩部分組成,一個屬性代碼(字串)和一個專案 ID(數字)。在另一個選項卡“位置”中有一堆空位置。每個位置都有主要屬性(字串)和較長字串中的一組次要屬性代碼。
我已將這兩個范圍分配給兩個唯一的陣列。
function matchcodes() {
var locss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Locations');
var lastlocRow = locss.getLastRow();
var newitems = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('New Items');
var lastNIRow = newitems.getLastRow();
var itemcodes = newitems.getRange("A1:B" lastNIRow).getValues();
var locations = locationssheet.getRange("A2:D" lastlocationRow).getValues();
Logger.log(itemcodes)
Logger.log(locations)}
我試圖做的是比較(itemcodes[i][0]將locations[j][2]專案屬性與位置主要屬性匹配)。如果字串匹配,我想復制itemcodes[i][1](ItemID) 并將其設定為locations[j][1]. 如果字串不匹配,請檢查locations[j][2]. 如果在 中沒有找到匹配的屬性locations[j][2],我想看看它是否作為子字串包含在locations[j][3](從頂部開始并遍歷整個輔助屬性串列。如果子字串代碼包含在loactions[j][3]我想采用相同的在第一個 IF 條件下動作。
一旦匹配了一個新專案,回圈就可以中斷,并且可以定位下一個專案itemcodes[i 1][0]。如果在主要或次要搜索中未找到匹配項,則還迭代到下一個新專案。
我正在努力撰寫條件陳述句來比較字串中的字串和子字串。
//for (var i = 0; i < itemcodes.length; i ) {
//for (var j = 0; j < locations.length; j ) {
//if (itemcodes[i][0] == locations[j][2]) {
// I want set the value of locations[j][1] with itemcodes[i][1]
}
// if no match is found in entire [j][2] column, search for substring in locations[j][3] column
//if item match is found, or no match is found in all of [j][2] or [j][3] break loop and iterate to [i 1][0] and start the next loop
輸入(3 次迭代) 結果
任何幫助將非常感激。或者,如果你能指出我類似的執行緒。(我沒有成功找到類似的例子)提前謝謝!
uj5u.com熱心網友回復:
嘗試:
function matchCodes() {
const newItems = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(`New Items`)
const locations = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(`Locations`)
const newItemsValues = newItems.getDataRange().getValues()
const locationsValues = locations.getDataRange().offset(1, 0).getValues()
newItemsValues.forEach(([attribute, id]) => {
const primaryTarget = locationsValues.findIndex(row => row[2] === attribute && row[1] === ``)
if (primaryTarget !== -1) return locationsValues[primaryTarget][1] = id
const secondaryTarget = locationsValues.findIndex(row => row[3].includes(attribute) && row[1] === ``)
if (secondaryTarget !== -1) return locationsValues[secondaryTarget][1] = id
})
locations.getDataRange().offset(1, 0).setValues(locationsValues)
}
學到更多:
- Array.findIndex()
- 解構賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492574.html
