掌握JS內置對象的常見用法,需要具體代碼示例
在使用 JavaScript 進行開發時,我們經常會和各種內置對象打交道。這些內置對象提供了豐富的功能和方法,能夠幫助我們實現各種復雜的邏輯和操作。學習掌握這些內置對象的常見用法,能夠提高我們的編碼效率和開發質量。本文將介紹幾個常見的 JS 內置對象,并給出具體的代碼示例。
- Math 對象
Math 對象提供了很多數學相關的方法,比如對數、三角函數、指數運算等。下面是幾個常用的示例代碼:
// 獲取一個隨機數 let randomNum = Math.random(); console.log(randomNum); // 求絕對值 let absNum = Math.abs(-10); console.log(absNum); // 求平方根 let sqrtNum = Math.sqrt(16); console.log(sqrtNum); // 求最大值 let maxNum = Math.max(1, 2, 3); console.log(maxNum); // 求最小值 let minNum = Math.min(1, 2, 3); console.log(minNum);
登錄后復制
- Date 對象
Date 對象用于處理日期和時間。它提供了許多方法,如獲取當前時間、設置時間、格式化輸出等。以下是幾個常用的代碼示例:
// 獲取當前時間 let currentDate = new Date(); console.log(currentDate); // 獲取年份 let year = currentDate.getFullYear(); console.log(year); // 獲取月份(從0開始計數,0代表一月) let month = currentDate.getMonth(); console.log(month); // 獲取日期 let day = currentDate.getDate(); console.log(day); // 設置日期 currentDate.setDate(10); console.log(currentDate); // 格式化輸出日期 let formattedDate = currentDate.toLocaleDateString(); console.log(formattedDate);
登錄后復制
- String 對象
String 對象用于處理字符串。它提供了很多方法,如獲取字符串長度、查找子串、替換字符串等。以下是幾個常用的代碼示例:
// 獲取字符串長度 let str = "Hello, world!"; let length = str.length; console.log(length); // 查找子串 let index = str.indexOf("world"); console.log(index); // 替換字符串 let newStr = str.replace("world", "JavaScript"); console.log(newStr); // 字符串分割 let splittedStr = str.split(","); console.log(splittedStr);
登錄后復制
- Array 對象
Array 對象用于處理數組。它提供了很多方法,如添加元素、刪除元素、遍歷數組等。以下是幾個常用的代碼示例:
// 創建一個空數組 let arr = []; // 添加元素 arr.push(1); arr.push(2); arr.push(3); console.log(arr); // 刪除元素 arr.pop(); console.log(arr); // 數組遍歷 arr.forEach(function(element) { console.log(element); });
登錄后復制
以上僅是對幾個常見的內置對象的簡單介紹和示例代碼。在實際開發中,還有很多其他的內置對象可供使用,如 RegExp 對象、JSON 對象等。通過不斷地學習和練習,我們能夠更深入地掌握這些內置對象的用法,提升自己的編程水平。