2017-09-12 21 views
0

我收到一个类型错误,指出在向html页面添加输入时,数组testA [i]是未定义的。我已经在阵列设置和我试图使用推送方法添加到阵列即([0] [货币])js中的未定义参数

function Test() { 

var testA = []; 
for (i = 0; i < 4; i++) { 
     this.currency = prompt("Please enter a 3-letter currency abbreviation", ""); 
     testA[i].push(currency); 
     } 
} 
var index = new Test(); 

enter image description here

的第二部分货币的值添加到阵列

任何帮助,为什么数组是未定义的,将不胜感激。

注意:我现在已经尝试testA.push(currency)和testA [i] = this.currency,并且仍然像以前一样得到相同的错误。

注意:最终版本应该让它遍历4个不同的问题,并且每次将这些问题添加到数组中。在循环结束时,应该创建一个新的数组变体,并将输入的新数据集添加到它。像 for(i = 0; i < 4; i++) { testA[i] = i; for(j = 0; j < 4; j++) { this.currency = prompt("Please enter a 3-letter currency abbreviation", ""); testA[i][j] = this.currency; } }

但在这个时候我只是想让它工作。

+0

忘记提到,这需要循环4个不同的部分。因此我需要货币价值在指数。 testA [i] [0] < - 这里。然后一旦循环结束,我就会上升1,并再次提出问题。testA [3] [currency] testA [2] [currency] testA [3] [currency] – soul6942

回答

5

对索引不使用push方法。你可以在数组本身上使用它。

替换此

testA[i].push(currency); 

有了这个

testA.push(currency); 
1

您需要在阵列上直接执行推送操作。

testA.push(currency); 

通过执行testA[index]您将收到持有价值。在JS中,如果index大于数组长度,它将始终返回undefined

因为你的数组是空的,所以你总是收到undefined

1

您正在混合使用两种不同的实现。

您可以使用直接分配。


要么你推新的值到数组。

var testA = []; 

for (i = 0; i < 4; i += 1) { 
    this.currency = prompt('...', ''); 

    testA.push(this.currency); 
} 

您应该使用第二个,这是最简单的soluce

1
testA[i] = this.currency OR testA.push(this.currency) 

使用修改功能下面

function Test() { 
     var testA = []; 
      for (i = 0; i < 4; i++) { 
        this.currency = prompt("Please enter a 3-letter currency abbreviation", ""); 
        testA[i] = this.currency; // use this.currency here if you 
        } 
      console.log(testA); 
      } 

var index = new Test();