Reputation: 11
1.hey guys,how do i separate these? 2.sorry im newb in this,but been cracking my head for a while,how to make this code write sentences separetly without writing them non stop?
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++) {
var y=Number(prompt("enter number from 10 to 30",0));
for(i=0;i<=9;i++) {
if(y==x[i]) {//checking every number in array
document.write("u right.<br>");
e=e+1;
}
else {
document.write("u wrong.<br>");//this writes every time it goes trough the loop,i tried breaking,but it just quits the loop on first number in array,i tried continue,no luck
}
}
}
if(e<5) {//amount of time you guessed right
document.write("u lose ");
}
else {
document.write("u win");
}
</script>
</body>
</html>
Upvotes: 0
Views: 69
Reputation: 2412
Use indexOf method of array for checking whether value is available in array or not.
If value is not available then return -1 else return position of that value.
<html>
<body>
<script type="text/javascript">
var x = [15,22,28,30,25,11,12,29,27,26];
var e = 0;
for (var c=1;c<=10;c++) {
var y = Number(prompt("enter number from 10 to 30",0));
x.indexOf(y) > 0?(document.write("u right.<br>"),e++):document.write("u r wrong.<br>");
}
e<5?document.write("u lose "):document.write("u win");
</script>
</body>
</html>
Upvotes: 0
Reputation: 4902
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++)
{
var y=Number(prompt("enter number from 10 to 30",0));
var right = false;
for(i=0;i<=9;i++)
{
if(y==x[i]) //checking every number in array
{
right = true;
}
}
if (right)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{document.write("u win");}
</script>
</body>
</html>
Your code can be optimized in many areas:
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var c=0;
while (c < 10)
{
c++;
var y=Number(prompt("enter number from 10 to 30",0));
if (x.indexOf(y) != -1)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{
document.write("u win");
}
</script>
</body>
</html>
Upvotes: 1