将 "Undefined" 替换为文本

Replace "Undefined" with Text

我正在尝试在显示已变为空的数组时替换 "undefined"。

这是该程序的简化版本,其中每次按下按钮时用户都会递减数组。当数组为空时,如果用户继续按下按钮,我希望文本替换 "undefined."

我玩过 "while" 语句以及 "typeof",但我似乎无法让它工作。

<script>
  basket = ['Apples', 'Bananas', 'Pears'];

  function showFruit() {
    var i = 0; // the index of the current item to show
    fruitDisplay = setInterval(function() {
        document.getElementById('fruit')
            .innerHTML = basket[i++]; // get the item and increment
        if (i == basket.length) i = 0; 
                                   // reset to first element if you've reached the end
    }, 100); //speed to display items

    var endFruitDisplay = setTimeout(function() {
        clearInterval(fruitDisplay);

        var index = basket.indexOf(document.getElementById('fruit').innerHTML);
        basket.splice(index, 1); //remove last shown

    }, 1000); //stop display after x milliseconds

    remain = basket.length;
    document.getElementById("remaining").innerHTML = remain;

    return showFruit;
}

    //if (typeof(basket) == undefined) {
    //fruit = 'Finished';
    //} 

</script>

    <h1><span id = 'fruit'></span> </h1>
    Remaining: <span id="remaining"></span>


 <button onclick="showFruit()">Random Fruit</button>

我看到注释的代码...试试...

if (typeof basket === "undefined") {
  fruit = 'Finished';
}

基本上,这是比较 typeofundefined 的正确方法。虽然你的变量typeof不会是undefined,所以...

您还可以检查数组长度...

if (basket.length === 0) {
  fruit = 'Finished';
}

只测试数组是否为空

if (basket.length == 0) {
    document.getElementById("fruit").innerHTML = "No fuits left";
} else {
    document.getElementById('fruit')
        .innerHTML = basket[i];
    i = (i + 1) % basket.length // increment with wraparound
}