Custom Functions (User-defined Functions) คือฟังก์ชันที่นักพัฒนาสร้างเอง ส่วน Built-in Functions คือฟังก์ชันที่ JavaScript เตรียมไว้ให้ใช้งานทันที (Native/Standard Library)
Custom Functions (ฟังก์ชันผู้ใช้กำหนด)
<script>
function functionName(parameterList) {
statements;
}
</script>
Built-in Functions (ฟังก์ชันสำเร็จรูป)
ตัวอย่าง String Methods:
| Method | คำอธิบาย |
|---|---|
charAt(index) | คืนตัวอักษรตำแหน่ง index |
charCodeAt(index) | คืน Unicode ค่าของตัวอักษรตำแหน่ง index |
concat(str) | รวมสตริง คืนสตริงใหม่ |
indexOf(searchValue) | หาตำแหน่งแรกที่เจอ คืน -1 ถ้าไม่เจอ |
slice(start, end) | ตัดสตริงสับสน (รองรับ index ติดลบ) |
split(separator) | แบ่งสตริงเป็นอาร์เรย์ |
toUpperCase() | แปลงเป็นตัวพิมพ์ใหญ่ |
toLowerCase() | แปลงเป็นตัวพิมพ์เล็ก |
trim() | ลบช่องว่างหน้า/หลัง |
replace(regexp, replacement) | แทนที่สตริง |
ตัวอย่าง Built-in: String concat()
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script>
var str1 = new String("This is string one");
var str2 = new String("This is string two");
var str3 = str1.concat(str2);
document.write("Concatenated String: " + str3);
</script>
</body>
</html>
ผลลัพธ์
Concatenated String: This is string oneThis is string two
หมวดหมู่ Built-in Functions หลัก
- Global:
parseInt,parseFloat,isNaN,isFinite,encodeURI,eval - Object:
Object.keys,Object.values,JSON.parse,JSON.stringify - Array:
map,filter,reduce,forEach,find,push,pop - String: ตารางด้านบน
- Math:
max,min,random,round,sqrt - Date:
Date.now,getTime,toISOString - Promise:
Promise.all,Promise.race
แนะนำ: ใช้ Built-in Functions ให้มากที่สุด (Optimized, Tested, Standard) สร้าง Custom เมื่อจำเป็นจริงๆ