2016-05-15 201 views
-2

編寫將在名爲cars的整數數組中循環的JavaScript代碼,並測試數組中的每個元素以查看它是否大於10.如果是,則顯示一個警告框。你不知道數組的長度,但是你的代碼必須測試數組的每個元素,而不管數組的長度。您不必聲明數組或將代碼寫入數組。我的功能似乎沒有工作

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo"></p> 



<script> 
function myFunction() { 
if (document.getElementById(cars[i]) > 10) 
    alert("I am an alert box!"); 

} 

var cars = [ 8, 9,10,11,12,13,14,15,16] 
var text = ""; 
var i; 
for (i = 0; i < cars.length; i++) { 
    text += cars[i] + "<br>"; 


myFunction(); 
document.getElementById("demo").innerHTML = text; 



} 


</script> 

</body> 
</html> 

有人可以指出我做錯了什麼。

+1

這個問題看起來像一個學校作業。 –

+0

是否要爲每輛車大於10的警報箱或列表中每輛車大於10的警報箱? – Keatinge

+0

如果'(document.getElementById(cars [i])> 10)'是錯誤的話,我自己找到答案如果'(cars [i]> 10)' –

回答

1

我不明白,爲什麼你的每個項目,有這麼多的代碼,只需循環並將其與十..

var cars = [8, 9, 10, 11, 12, 13, 14, 15, 16]; 
for (var i = 0; i < cars.length; i++) { 
    if (cars[i] > 10) { 
    alert(cars[i] + " is greater than 10"); 
    } 
} 
0

走到完整的愚蠢方式

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo"></p> 



<script> 
function myFunction() { 
if (cars[i] > 10) //<-----was if (document.getElementById(cars[i]) > 10) 
    alert("I am an alert box!"); 

} 

var cars = [ 8, 9,10,11,12,13,14,15,16] 
var text = ""; 
var i; 
for (i = 0; i < cars.length; i++) { 
    text += cars[i] + "<br>"; 


myFunction(); 
document.getElementById("demo").innerHTML = text; 



} 


</script> 

</body> 
</html> 
0

你最好關只用Array.prototype.every

var cars = [8, 9, 10, 11, 12, 13, 14, 15, 16]; 
 

 
if (cars.every(x => x > 10)) 
 
    alert('Every car is greater than 10.'); 
 
else alert('False. Every car is not greater than 10.'); 
 
// you can remove the else statement; just showing you that it works.