[英]Undefined error when trying to access Array value of Map by index
我的代碼如下:
let myMap = new Map(
[["MMP", ["H1", "-"]], ["TTP", ["H1", "*"]]
);
var array1 = ["MMP", 1, 2]; // array1[0] is the key I want to find in my map
console.log(myMap.get(array1[0]); // Works: gets the values for the given key => [value1,value2]
console.log(myMap.get('example key')[0]); // Works: gets the first element of the array value
console.log(myMap.get(array1[0])[0]); // TypeError: Cannot read property '0' of undefined
// array1[0] is the same as 'example key'
我看不到我在這里做錯了什么。 array1[0] 是字符串類型,與我的 map 中的鍵相同。
非常感激你的幫助!
編輯:添加更完整的代碼:
var tagSheet = SpreadsheetApp.getActive().getSheetByName('values1');
var docSheet = SpreadsheetApp.getActive().getSheetByName('values2');
var myTagRange = tagSheet.getDataRange();
var myDocRange = docSheet.getDataRange();
var tagValues = myTagRange.getValues();
var docValues = myDocRange.getValues();
function compare(){
var array1 = [];
var columnToCheck = docSheet.getRange("A:A").getValues();
// Get the last row based on the data range of a single column.
var docLastColumn = getLastRowSpecial(columnToCheck);
var tagMap = new Map(getTagMap());
//Loop over values2 sheet
for(var n=3;n<docLastColumn;n++){
array1 = docValues[n][0].split("*");
if( tagMap.get(array1[0])[0] === 't1'){ //Error here
Logger.log('passed');
}
}
}
function getTagMap() {
//Select the column we will check for the first blank cell
var columnToCheck = tagSheet.getRange("A:A").getValues();
// Get the last row based on the data range of a single column.
var lastRow = getLastRowSpecial(columnToCheck);
let myMap = new Map();
for(var n=1;n<lastRow;n++){
myMap.set(tagValues[n][0].trim(), [tagValues[n][1].trim(),tagValues[n][2].trim()]);
}
return myMap;
};
function getLastRowSpecial(range){
var rowNum = 0;
var blank = false;
for(var row = 0; row < range.length; row++){
if(range[row][0] === "" && !blank){
rowNum = row;
blank = true;
}else if(range[row][0] !== ""){
blank = false;
}
}
return rowNum;
}
為了使這種重現性生成一個谷歌表,其中第一個表名為 values1,第二個表名為 values2。 您必須在 Google Apps 腳本上運行它。
請參閱圖像以獲取示例值:
值1張
值2表
tagMap
沒有array1[0]
鍵 => 訪問undefined
的屬性0
時返回undefined
=> 錯誤
TypeError:無法讀取未定義的屬性“0”
這是因為,屬性[0]
的訪問就像它是一個數組而不是未定義的一樣。
使用代碼防護來相應地檢查和修改結果。
const thisMapValue = tagMap.get(array1[0]);
if(thisMapValue && thisMapValue[0] === 't1'){ //ensures `thisMapValue` is not undefined before accessing `[0]` property
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.