2017-09-05 51 views
2

我正在構建基於電子表格數據的Google Slide。每張幻燈片都會有關於服裝的細節信息,如裙子或連衣褲,但是當我需要在一頁上顯示上衣和裙子的細節時,我遇到了一個問題。Javascript - 檢查陣列lookahead匹配

在源電子表格中,我使用1,2,3表示法來訂購幻燈片,如果有輔助產品,我使用的是1.1,2.1,3.1等,因此數組中的順序最終成爲

[1, 2, 2.1, 3, 4, 4.1 ] //...etc 

我想要做的是在一次調用中將幻燈片的所有細節都傳遞給Slides API。爲此,我想在創建「2」幻燈片的調用中傳遞「2.1」數組。要做到這一點,我需要對陣列進行前瞻。

下面是我用來測試的代碼和我的JSFiddle在這裏。

var foo = new Array(); 
var firstProduct; 
var secondProduct = ""; 
var order; 
foo = [ 
    [1, "one2", "one3"], 
    [2, "two2", "two3"], 
    [2.1, "two21", "two31"], 
    [3, "three2", "three3"] 
]; 
for (var i = 0; i < foo.length; i++) { 
    firstProduct = foo[i][0]; 
    if (foo[i][0] <= foo.length) { 
    secondProduct = foo[i + 1][0]; 
    if (typeof secondProduct !== 'undefined' && Math.floor(firstProduct) == Math.floor(secondProduct)) { 
     alert("Match " + firstProduct + " " + secondProduct); 
     i++; 
    } 
    else { 
     alert("No match - firstProduct" + firstProduct); 
     } 
    } 
    else { 
     alert("last " + firstProduct); 
    } 
} 

正如你可以看到它拋出這個錯誤:

VM3349:59遺漏的類型錯誤:未定義 在在window.onload無法讀取屬性 '0'(VM3349:59)

+1

和這背後的原因是什麼?你需要一個新的數據結構還是隻需要一個對話框? –

+0

我需要一個新的數據結構。我現在的函數有這些參數:populateSlide(order,styleCode,styleName,styleColours,deliveryMonth,wholesalePrice,retailPrice,leftImage,rightImage,season,counter); - 我需要擴展它以包含第二個產品細節。 – Samuurai

+0

請爲示例添加所需的數據結構。 –

回答

0

你是訪問未定義foo的[I + 1],你可以做

var foo = new Array(); 
 
var firstProduct; 
 
var secondProduct = ""; 
 
var order; 
 
foo = [ 
 
    [1, "one2", "one3"], 
 
    [2, "two2", "two3"], 
 
    [2.1, "two21", "two31"], 
 
    [3, "three2", "three3"] 
 
]; 
 
for (var i = 0; i < foo.length; i++) { 
 
    firstProduct = foo[i][0]; 
 
    if (foo[i][0] <= foo.length && foo[i+1]) { 
 
    secondProduct = foo[i + 1][0]; 
 
    if (typeof secondProduct !== 'undefined' && Math.floor(firstProduct) == Math.floor(secondProduct)) { 
 
     alert("Match " + firstProduct + " " + secondProduct); 
 
     i++; 
 
    } 
 
    else { 
 
     alert("No match - firstProduct" + firstProduct); 
 
     } 
 
    } 
 
    else { 
 
     alert("last " + firstProduct); 
 
    } 
 
}

這會運行,直到它們存在一個富[i + 1]

+0

這將是我 marvel308

+0

這絕對修復了錯誤。謝謝!任何想法,如果我這樣做的方式是有效的? – Samuurai