我正在尝试更换" undefined"显示已变空的数组时。
这是程序的简化版本,每次按下按钮时,用户都会递减数组。当数组为空时,如果用户继续按下按钮,我希望替换文本" undefined。"
我玩过"而#34;陈述,以及" 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>
答案 0 :(得分:2)
只测试数组是否为空。
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
}
答案 1 :(得分:0)
我看到评论的代码......试试......
if (typeof basket === "undefined") {
fruit = 'Finished';
}
基本上,这是将typeof
与undefined
进行比较的正确方法。虽然你的变量typeof不会被定义,所以......
您还可以检查数组长度......
if (basket.length === 0) {
fruit = 'Finished';
}