自定义函数返回正确的结果,并且未定义.为什么

Custom function returns correct results and also undefined. Why is that?

本文关键字:未定义 为什么 结果 返回 自定义函数      更新时间:2023-09-26

我正在研究我的JavaScript技能,我写了那一小段代码:

var Intel = ["a", "v", "f", "c", "s"];
if (Intel && Intel.constructor == Array) {
    alert('correct');
} else {
    alert("false");
}
alert(Intel.length);
function showThemAll() {
    // this function will alert every single data of the table
    for (var i = 0; i <= Intel.length; i++) {
        //alert of the data
        alert(Intel[i]);
    }
}
showThemAll();

我不明白为什么在正确的结果下,我会收到一个未定义的警报。

你能帮帮我吗?

i <= Intel.length

数组是零索引,因此您用=读取

的数组太多了

将其更改为以下内容,您将不会得到未定义的

for (var i = 0; i < Intel.length; i++) {

因为你正在运行你的循环直到i <= Intel.length.

应该是i < Intel.length

数组

索引从 0 开始,因此以小于数组长度 1 结束。

相关文章: