งบเงื่อนไขใน Javaสคริปต์: if, else และ else if

Javaคำสั่งเงื่อนไขสคริปต์

ประโยคเงื่อนไขส่วนใหญ่มีสามประเภท Javaต้นฉบับ

  1. ถ้างบ: คำสั่ง 'if' รันโค้ดตามเงื่อนไข
  2. ถ้า…อย่างอื่นคำสั่ง: คำสั่ง if…else ประกอบด้วยโค้ดสองช่วงตึก เมื่อเงื่อนไขเป็นจริง จะดำเนินการบล็อกแรกของโค้ด และเมื่อเงื่อนไขเป็นเท็จ จะดำเนินการบล็อกที่สองของโค้ด
  3. คำสั่ง if…else if…else: เมื่อจำเป็นต้องทดสอบหลายเงื่อนไขและจำเป็นต้องดำเนินการบล็อกโค้ดที่แตกต่างกันตามเงื่อนไขที่เป็นจริง จะใช้คำสั่ง if…else if…else

วิธีใช้คำสั่งแบบมีเงื่อนไข

คำสั่งแบบมีเงื่อนไขใช้ในการตัดสินใจขั้นตอนการดำเนินการตามเงื่อนไขต่างๆ หากเงื่อนไขเป็นจริง คุณสามารถดำเนินการอย่างหนึ่งได้ และหากเงื่อนไขเป็นเท็จ คุณก็ดำเนินการอื่นได้

ใช้คำสั่งแบบมีเงื่อนไขใน Javaต้นฉบับ

ถ้าคำสั่ง

ไวยากรณ์:

if(condition)
{
	lines of code to be executed if condition is true
}

คุณสามารถใช้ได้ if คำสั่งถ้าคุณต้องการตรวจสอบเฉพาะเงื่อนไขเฉพาะ

ลองด้วยตัวเอง:

<html>
<head>
	<title>IF Statments!!!</title>
	<script type="text/javascript">
		var age = prompt("Please enter your age");
		if(age>=18)
		document.write("You are an adult <br />");
		if(age<18)
		document.write("You are NOT an adult <br />");
	</script>
</head>
<body>
</body>
</html>

ถ้า…คำสั่งอื่น

ไวยากรณ์:

if(condition)
{
	lines of code to be executed if the condition is true
}
else
{
	lines of code to be executed if the condition is false
}

คุณสามารถใช้ได้ If….Else คำสั่งหากคุณต้องตรวจสอบเงื่อนไขสองข้อและรันโค้ดชุดอื่น

ลองด้วยตัวเอง:

<html>
<head>
	<title>If...Else Statments!!!</title>
	<script type="text/javascript">
		// Get the current hours
		var hours = new Date().getHours();
		if(hours<12)
		document.write("Good Morning!!!<br />");
		else
		document.write("Good Afternoon!!!<br />");
	</script>
</head>
<body>
</body>
</html>

ถ้า…อื่นถ้า…คำสั่งอื่น

ไวยากรณ์:

if(condition1)
{
	lines of code to be executed if condition1 is true
}
else if(condition2)
{
	lines of code to be executed if condition2 is true
}
else
{
	lines of code to be executed if condition1 is false and condition2 is false
}

คุณสามารถใช้ได้ If….Else If….Else คำสั่งถ้าคุณต้องการตรวจสอบมากกว่าสองเงื่อนไข

ลองด้วยตัวเอง:

<html>
<head>
	<script type="text/javascript">
		var one = prompt("Enter the first number");
		var two = prompt("Enter the second number");
		one = parseInt(one);
		two = parseInt(two);
		if (one == two)
			document.write(one + " is equal to " + two + ".");
		else if (one<two)
			document.write(one + " is less than " + two + ".");
		else
			document.write(one + " is greater than " + two + ".");
	</script>
</head>
<body>
</body>
</html>