返回

单行 JavaScript 代码让编码更轻松

前端

在开发过程中,我们经常需要编写大量重复性代码,这不仅浪费时间,而且容易出错。幸运的是,JavaScript 提供了许多单行代码来简化我们的开发。

这些单行代码可以帮助我们快速完成各种常见任务,例如:

  • 获取元素的属性值
  • 设置元素的属性值
  • 查找元素
  • 遍历数组
  • 排序数组
  • 过滤数组
  • 创建新的数组
  • 连接字符串
  • 拆分字符串
  • 替换字符串
  • 编码/解码字符串
  • 生成随机数字
  • 获取当前时间
  • 延迟函数执行
  • 绑定事件监听器
  • 移出事件监听器
  • 等等

下面列举了 25 个我经常使用的 JavaScript 单行代码。这些代码可以大大优化你的开发效率,而且兼顾编码的优雅性。

// 获取元素的属性值
const value = document.getElementById('myElement').value;

// 设置元素的属性值
document.getElementById('myElement').value = 'Hello World';

// 查找元素
const element = document.querySelector('.my-class');

// 遍历数组
const array = [1, 2, 3].forEach((item) => {
  console.log(item);
});

// 排序数组
const sortedArray = array.sort((a, b) => a - b);

// 过滤数组
const filteredArray = array.filter((item) => item > 2);

// 创建新的数组
const newArray = array.map((item) => item * 2);

// 连接字符串
const str = 'Hello ' + 'World';

// 拆分字符串
const splitStr = str.split(' ');

// 替换字符串
const newStr = str.replace('Hello', 'Hi');

// 编码/解码字符串
const encodedStr = encodeURIComponent(str);
const decodedStr = decodeURIComponent(encodedStr);

// 生成随机数字
const randomNum = Math.random();

// 获取当前时间
const date = new Date();

// 延迟函数执行
setTimeout(() => {
  console.log('Hello World');
}, 1000);

// 绑定事件监听器
document.getElementById('myElement').addEventListener('click', () => {
  console.log('Hello World');
});

// 移出事件监听器
document.getElementById('myElement').removeEventListener('click', () => {
  console.log('Hello World');
});

我希望这些代码能够帮助你提高 JavaScript 编码效率,并为你带来更多的编码乐趣。