gpt4 book ai didi

javascript - 类型错误 : arrayal[i] is undefined but it is defined

转载 作者:行者123 更新时间:2023-11-28 04:51:38 24 4
gpt4 key购买 nike

我有一个像这样创建的数组:

var gelenveri = document.getElementById("cakalinput").value;

var arrayal = [];

arrayal = gelenveri.split(" ");

我在函数中使用这个 arrayal,但在另一个 for 循环中的 while 语句中出现错误(TypeError: arrayal[i] 未定义,但已定义):

while(((!(arrayal[i].indexOf('%') > -1)) || (arrayal[i] != "-") )){

temizarray[j] = temizarray[j] + arrayal[i];
i++;


}

当我尝试查看 typeof(arrayal[i]) 时,它是字符串类型。我花了一个小时都无法解决这个问题。有什么想法吗?

这是我的整个代码:

function cakallik() {
var gelenveri = document.getElementById("cakalinput").value;
var arrayal = [];
arrayal = gelenveri.split(" ");
var uzunluk = arrayal.length;
var temizarray = [];
var j = 0;
var i = 0;

for (; i < uzunluk;) {
temizarray[j] = arrayal[i]; //ilk satır alındı
i++;
j++;
temizarray[j] = arrayal[i]; //ikincisatır alındı
i++;
j++;
temizarray[j] = arrayal[i]; //üçüncü satır alındı
i++;
j++;
temizarray[j] = arrayal[i]; //dördüncü alındı
i++;
j++;
temizarray[j] = arrayal[i]; // beşinci alındı
i++;

while (arrayal[i] != "-") {
temizarray[j] = temizarray[j] + arrayal[i];
i++;
}

i++;
j++;
temizarray[j] = arrayal[i];
i++;
console.log(typeof (arrayal[i]));

while (((!(arrayal[i].indexOf('%') > -1)) || (arrayal[i] != "-"))) {
temizarray[j] = temizarray[j] + arrayal[i];
i++;
}

i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
i++;
i++;
j++;
temizarray[j] = arrayal[i];
i++;
j++;
temizarray[j] = arrayal[i];
}

console.log(temizarray);
}

最佳答案

arrayal[i] is undefined

错误信息非常清楚。虽然 arrayal 已定义,但 arrayal[i] 未定义,因为您试图访问该数组中未出现的元素。

简而言之,你的数组 arrayal 长度小于 i,你应该在 while 中添加一个条件来检查 arrayal 的长度。

while(arrayal.length < i && ((!(arrayal[i].indexOf('%') > -1)) || (arrayal[i] != "-") )){

temizarray[j] = temizarray[j] + arrayal[i];
i++;


}

关于javascript - 类型错误 : arrayal[i] is undefined but it is defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com