2017-09-05 36 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