发布于 2026-01-06 0 阅读
0

22 个你 99% 的时间都会用到的 JavaScript 函数💯🔥

22 个你 99% 的时间都会用到的 JavaScript 函数💯🔥

以下函数对于 Web 开发和 JavaScript 编程至关重要,它们简化了诸如使用旧版和新版 console.log()进行调试 操作 DOM 以及处理 JSON 数据等任务。

了解和使用这些函数就像构建这门语言基础的骨架。

掌握这些工具肯定也能简化编码过程,从而带来良好的开发体验。


太长不看

控制台和调试
-> console.log(...args)

计时
-> 设置超时时间(回调函数,延迟)
-> 设置间隔时间(回调函数,间隔)

DOM 操作和事件处理
-> querySelectorAll(selector)
-> addEventListener(event, callback)

JSON 处理
-> JSON.parse(jsonString)
-> JSON.stringify(object)

数组操作(高阶函数)
-> forEach(回调函数)
-> map(回调函数)
-> filter(回调函数)
-> reduce(回调函数, 初始值)

数组操作
-> slice(start, end)
-> splice(start, deleteCount, ...items)
-> indexOf(element)
-> includes(element)
-> sort(compareFunction)
-> reverse()
-> isArray(value)

字符串操作
-> split(分隔符)
-> join(分隔符)
-> toLowerCase(), toUpperCase()
-> trim()


控制台和调试:

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

⇒ 将消息或对象输出到控制台以进行调试。

// console.log(...args)

console.log("Hello World!");
Enter fullscreen mode Exit fullscreen mode

定时:

0️⃣2️⃣ setTimeout(回调函数,延迟)

⇒ 在指定的延迟时间(以毫秒为单位)后执行函数。

0️⃣3️⃣ setInterval(callback, interval)

⇒ 按指定时间间隔重复执行函数。

// 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
Enter fullscreen mode Exit fullscreen mode

DOM 操作和事件处理:

0️⃣4️⃣ querySelectorAll(selector)

⇒ 返回一个 NodeList,其中包含所有与指定选择器匹配的元素。

0️⃣5️⃣ addEventListener(event, callback)

⇒ 将事件处理函数附加到 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!');
});
Enter fullscreen mode Exit fullscreen mode

JSON 处理:

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

⇒ 解析 JSON 字符串并返回 JavaScript 对象。

0️⃣7️⃣ JSON.stringify(object)

⇒ 将 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"}
Enter fullscreen mode Exit fullscreen mode

数组操作(高阶函数):

0️⃣8️⃣ forEach(回调)

⇒ 对数组中的每个元素执行一次提供的函数。

0️⃣9️⃣ map(回调)

⇒ 创建一个新数组,其中包含对每个元素调用提供的函数的结果。

1️⃣0️⃣ 过滤器(回调)

⇒ 创建一个新数组,其中包含满足给定条件的元素。

1️⃣1️⃣ reduce(回调函数,初始值)

⇒ 通过对数组中的每个元素应用函数,将数组简化为单个值。

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
Enter fullscreen mode Exit fullscreen mode

数组操作:

1️⃣2️⃣ 切片(开始,结束)

⇒ 返回数组中指定起始索引和结束索引之间的部分数组的浅拷贝。

1️⃣3️⃣ splice(start, deleteCount, ...items)

⇒ 通过删除/替换元素和/或添加新元素来更改数组内容。

1️⃣4️⃣ indexOf(element)

⇒ 返回给定元素在数组中可以找到的第一个索引,如果不存在则返回 -1。

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

⇒ 判断数组中是否包含某个元素,返回 true 或 false。

1️⃣6️⃣ sort(compareFunction)

⇒ 根据提供的函数或默认排序顺序对数组元素进行排序。

1️⃣7️⃣ 反转()

⇒ 反转数组中元素的顺序。

1️⃣8️⃣ isArray(value)

⇒ 检查给定值是否为数组,返回 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
Enter fullscreen mode Exit fullscreen mode

字符串操作:

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

⇒ 根据指定的分隔符将字符串拆分成子字符串数组。

2️⃣0️⃣ join(分隔符)

⇒ 将数组中的所有元素连接成一个字符串,并用指定的分隔符分隔。

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

⇒ 将字符串转换为小写或大写。

2️⃣2️⃣ trim()

⇒ 删除字符串两端的空格。

// 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!"
Enter fullscreen mode Exit fullscreen mode

🙌 最后想说的话

在我们结束对上述功能的讨论之际,请分享一下您的见解。

在您的 Web 开发或主要 JavaScript 项目中,您认为还有哪些功能是必不可少的?

欢迎在下方评论区分享您的想法和实用功能!

希望你喜欢这篇文章!❤️

请通过Linktree 联系我。

编程愉快!🚀
感谢 22097 位用户的支持!🤗

文章来源:https://dev.to/arjuncodess/18-javascript-functions-youll-use-99-of-the-time-2bl4