下面的函數對於 Web 開發和 JavaScript 程式設計來說是基礎,它們簡化了任務,例如*使用新舊 console.log()***進行偵錯操作 DOM 以及處理 JSON 資料。**

了解和使用這些函數就像建立該語言的基礎支柱一樣。

掌握這些工具也肯定會簡化編碼流程,進而帶來良好的開發人員體驗。


長話短說

控制台和除錯

-> 控制台.log(...args)

定時

-> setTimeout(回呼, 延遲)

-> setInterval(回呼, 間隔)

DOM 操作和事件處理

-> 查詢選擇器全部(選擇器)

-> addEventListener(事件,回呼)

JSON 處理

-> JSON.parse(jsonString)

-> JSON.stringify(物件)

陣列運算(高階函數)

-> forEach(回呼)

-> 地圖(回呼)

-> 過濾器(回調)

-> 減少(回調,初始值)

陣列運算

-> 切片(開始,結束)

-> 拼接(開始,刪除計數,...專案)

->indexOf(元素)

-> 包含(元素)

-> 排序(比較函數)

-> 反向()

-> isArray(值)

字串操作

-> 分割(分隔符號)

-> 連接(分隔符號)

-> toLowerCase(), toUpperCase()

-> 修剪()


控制台和除錯:

0️⃣1️⃣ console.log(...args)

⇒ 將訊息或物件輸出到控制台以進行偵錯。

// console.log(...args)

console.log("Hello World!");

定時:

0️⃣2️⃣ setTimeout(回呼、延遲)

⇒ 在指定的延遲(以毫秒為單位)後執行函數。

0️⃣3️⃣ setInterval(回調,間隔)

⇒ 以指定的時間間隔重複執行某個功能。

// setTimeout(callback, delay)

setTimeout(function() {
    console.log("This message will appear after 3 seconds.");
}, 3000);
// Runs the anonymous function after 3000 milliseconds (3 seconds)

// setInterval(callback, interval)

function printCounter() {
    let count = 0;
    setInterval(function() {
        console.log("Count:", count++);
    }, 1000);
}

printCounter(); // Prints count every second

DOM 操作與事件處理:

0️⃣4️⃣ querySelectorAll(選擇器)

⇒ 傳回一個 NodeList,其中包含與指定選擇器相符的所有元素。

0️⃣5️⃣ addEventListener(事件,回呼)

⇒ 將事件處理函數附加到 HTML 元素。

// querySelectorAll(selector)
console.log("querySelectorAll(selector)");
const container = document.getElementById('container');
const links = container.querySelectorAll('a'); 
// Accessing the href attribute of each link

// Iterate over the NodeList
links.forEach(link => {
    console.log(link.href);
});

// addEventListener(event, callback)
console.log("addEventListener(event, callback)");
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
    console.log('Button clicked!');
});

JSON 處理:

0️⃣6️⃣ JSON.parse(jsonString)

⇒ 解析 JSON 字串並傳回 JavaScript 物件。

0️⃣7️⃣ JSON.stringify(物件)

⇒ 將 JavaScript 物件轉換為 JSON 字串。

// JSON.parse(jsonString)
console.log("JSON.parse(jsonString)");
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name);
// Output: John
console.log(jsonObject.age); 
// Output: 30
console.log(jsonObject.city);
// Output: New York

// JSON.stringify(object)
console.log("JSON.stringify(object)");
const person = { name: 'John', age: 30, city: 'New York' };
const jsonString2 = JSON.stringify(person);

console.log(jsonString2);
// Output: {"name":"John","age":30,"city":"New York"}

陣列運算(高階函數):

0️⃣8️⃣ forEach(回呼)

⇒ 對每個陣列元素執行一次提供的函數。

0️⃣9️⃣地圖(回調)

⇒ 使用對每個元素呼叫提供的函數的結果來建立一個新陣列。

1️⃣0️⃣過濾器(回呼)

⇒ 建立一個新陣列,其中的元素滿足給定的條件。

1️⃣1️⃣減少(回調,初始值)

⇒ 透過對每個元素應用函數將陣列縮減為單一值。

const numbers = [1, 2, 3, 4, 5];

// forEach(callback)
console.log("forEach:");
numbers.forEach(num => {
    console.log(num);
});

// Output:
// 1
// 2
// 3
// 4
// 5

// map(callback)
const doubledNumbers = numbers.map(num => num * 2);
// Output: [2, 4, 6, 8, 10]

// filter(callback)
const evenNumbers = numbers.filter(num => num % 2 === 0);
// [2, 4]

// reduce(callback, initialValue)
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// 15

陣列操作:

1️⃣2️⃣片(開始,結束)

⇒ 傳回指定起始索引和結束索引之間的陣列部分的淺表副本。

1️⃣3️⃣ 拼接(開始,刪除計數,...專案)

⇒ 透過刪除/取代元素和/或新增元素來變更陣列內容。

1️⃣4️⃣indexOf(元素)

⇒ 傳回在陣列中可以找到給定元素的第一個索引,如果不存在則傳回 -1。

1️⃣5️⃣包含(元素)

⇒ 判斷陣列是否包含某個元素,傳回 true 或 false。

1️⃣6️⃣排序(比較函數)

⇒ 根據提供的函數或預設排序順序對陣列元素進行排序。

1️⃣7️⃣反向()

⇒ 反轉陣列中元素的順序。

1️⃣8️⃣ isArray(值)

⇒ 檢查給定值是否為陣列,傳回 true 或 false。

// slice(start, end)
const array = [1, 2, 3, 4, 5];
const slicedArray = array.slice(1, 4);
console.log("slice:", slicedArray);
// Output: [2, 3, 4]

// splice(start, deleteCount, ...items)
const spliceArray = [1, 2, 3, 4, 5];
spliceArray.splice(2, 2, 'a', 'b');
console.log("splice:", spliceArray);
// Output: [1, 2, "a", "b", 5]

// indexOf(element)
const indexOfArray = ['apple', 'banana', 'cherry'];
const indexOfCherry = indexOfArray.indexOf('cherry');
console.log("indexOf:", indexOfCherry);
// Output: 2

// includes(element)
const includesArray = [1, 2, 3, 4, 5];
const includesValue = includesArray.includes(3);
console.log("includes:", includesValue);
// Output: true

// sort(compareFunction)
const sortArray = [3, 1, 4, 1, 5];
sortArray.sort((a, b) => a - b);
console.log("sort:", sortArray);
// Output: [1, 1, 3, 4, 5]

// reverse()
const reverseArray = ['a', 'b', 'c', 'd'];
reverseArray.reverse();
console.log("reverse:", reverseArray);
// Output: ['d', 'c', 'b', 'a']

// isArray(value)
const isArrayValue = [1, 2, 3];
const isArray = Array.isArray(isArrayValue);
console.log("isArray:", isArray);
// Output: true

字串操作:

1️⃣9️⃣分割(分隔符號)

⇒ 根據指定的分隔符號將字串分割為子字串陣列。

2️⃣0️⃣加入(分隔符號)

⇒ 將陣列的所有元素連接成一個字串,並以指定的分隔符號分隔。

2️⃣1️⃣ toLowerCase(), toUpperCase()

⇒ 將字串轉換為小寫或大寫。

2️⃣2️⃣修剪()

⇒ 刪除字串兩端的空格。

// split(separator)
const sentence = "Hello, world! How are you?";
const words = sentence.split(' ');
console.log("split:", words);
// Output: ["Hello,", "world!", "How", "are", "you?"]

// join(separator)
const fruits = ['Apple', 'Banana', 'Orange'];
const fruitString = fruits.join(', ');
console.log("join:", fruitString);
// Output: "Apple, Banana, Orange"

// toLowerCase(), toUpperCase()
const mixedCase = "Hello WoRLd";
const lowerCase = mixedCase.toLowerCase();
const upperCase = mixedCase.toUpperCase();
console.log("toLowerCase:", lowerCase);
// Output: "hello world"
console.log("toUpperCase:", upperCase);
// Output: "HELLO WORLD"

// trim()
const stringWithWhitespace = "   Hello, world!   ";
const trimmedString = stringWithWhitespace.trim();
console.log("trim:", trimmedString);
// Output: "Hello, world!"

🙌 最後的想法

當我們結束對上述功能的討論時,我請您分享您的見解。

您認為在 Web 開發或主要是 JavaScript 專案中還需要哪些其他功能?

請隨時在下面的評論中分享您的想法和有用的功能!

我希望你喜歡這篇文章! ❤️

與我聯絡: Linktree。

快樂編碼! 🚀

感謝22097! 🤗


原文出處:https://dev.to/arjuncodess/18-javascript-functions-youll-use-99-of-the-time-2bl4


共有 0 則留言