JavaScript中的20个小技巧

  1. 箭头函数可在没有参数时更简洁

箭头函数用于定义并创建函数的常用方式。如果没有参数,则可以使用下面的代码:

const logMessage = () => {
  console.log('Hello, World!');
};
  1. 使用setInterval()实现计时器

setInterval()是一个用于重复调用函数的内置函数。下面是一个setInterval()计时器的例子:

let count = 0;
const intervalId = setInterval(() => {
  console.log(count);
  count++;
  if (count > 5) {
    clearInterval(intervalId);
  }
}, 1000);
  1. 数组查找/搜索

使用Array.find()方法可以快速查找数组中的一个对象。下面是一个例子:

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' },
];
const user = users.find((user) => user.id === 2);
console.log(user); // { id: 2, name: 'Jane' }
  1. 字符串重复

使用字符串重复技巧可以将某个字符串重复多次。下面是一个例子:

const message = 'Hello, World! ';
const repeatedMessage = message.repeat(3);
console.log(repeatedMessage); // "Hello, World! Hello, World! Hello, World! "
  1. 数字格式化

通过使用Intl.NumberFormat可以格式化数字, 下面是一个例子:

const number = 12345.6;
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});
console.log(formatter.format(number)); // "$12,345.60"
  1. 将对象数组转换为对象

使用reduce()方法将对象数组转换为单个对象。这是一个例子:

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' },
];
const usersObject = users.reduce((obj, user) => {
  obj[user.id] = user;
  return obj;
}, {});
console.log(usersObject);
/*
{
  "1": {
    "id": 1,
    "name": "John"
  },
  "2": {
    "id": 2,
    "name": "Jane"
  },
  "3": {
    "id": 3,
    "name": "Bob"
  }
}
*/
  1. 空字符串检查

使用短路运算符进行空字符串检查,这是一个例子:

const name = '';
const displayName = name || 'Anonymous';
console.log(displayName); // "Anonymous"
  1. 使用Object.values()获取对象值

使用Object.values()获取对象的值。这是一个例子:

const user = {
  id: 1,
  name: 'John',
  age: 30,
};
const values = Object.values(user);
console.log(values); // [1, "John", 30]
  1. 解构对象元素

使用对象解构可以快速创建变量并设置其值。这是一个例子:

const user = {
  id: 1,
  name: {
    first: 'John',
    last: 'Doe',
  },
};
const {
  id,
  name: { first, last },
} = user;
console.log(`${first} ${last} (${id})`); // "John Doe (1)"
  1. Object.entries()函数

使用Entries()函数将对象转换成键-值对数组,这是一个例子:

const user = {
  id: 1,
  name: 'John',
  age: 30,
};
const entries = Object.entries(user);
console.log(entries); // [["id", 1], ["name", "John"], ["age", 30]]
  1. Async/await

使用async/await来处理异步操作。这是一个例子:

async function getUser() {
  const response = await fetch('/api/user');
  const user = await response.json();
  return user;
}
  1. 将图片转换为Base64格式

使用Canvas API可以将图片转换成Base64格式,这是一个例子:

const img = document.createElement('img');
img.src = 'example.png';
img.onload = () => {
  const canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  const context = canvas.getContext('2d');
  context.drawImage(img, 0, 0);
  const base64 = canvas.toDataURL('image/png');
};
  1. 数组中过滤空值

使用Boolean()函数过滤数组中的空值,这是一个例子:

const array = ['apple', null, 'banana', undefined, '', 'orange'];
const filteredArray = array.filter(Boolean);
console.log(filteredArray); // ["apple", "banana", "orange"]
  1. 检查对象是否为空

使用Object.keys()检查对象是否为空,这是一个例子:

const obj = {};
const isEmpty = Object.keys(obj).length === 0;
console.log(isEmpty); // true
  1. 使用reduce()合并数组中的值

使用reduce()合并数组中的值,这是一个例子:

const numbers = [10, 20, 30];
const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum); // 60
  1. 数组去重

使用Set()和Array.from()方法实现数组去重,这是一个例子:

const array = [1, 2, 2, 3, 3, 3, 4, 5, 5];
const uniqueArray = Array.from(new Set(array));
console.log(uniqueArray); // [1, 2, 3, 4, 5]
  1. 字符串在数组中搜索

使用字符串的indexOf()方法在数组中搜索字符串,这是一个例子:

const array = ['apple', 'banana', 'orange'];
const searchString = 'banana';
const index = array.indexOf(searchString);
console.log(index); // 1
  1. 使用rest参数传递变量

使用rest参数传递变量可以将函数定义更加灵活,这是一个例子:

function sum(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5, 6, 7)); // 22
  1. 筛选数组

使用Array.filter()方法筛选数组,这是一个例子:

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' },
];
const filteredUsers = users.filter((user) => user.id !== 2);
console.log(filteredUsers);
/*
[
  {
    "id": 1,
    "name": "John"
  },
  {
    "id": 3,
    "name": "Bob"
  }
]
*/
  1. 正则表达式搜索

使用正则表达式搜索字符串,这是一个例子:

const text = 'The quick brown fox jumps over the lazy dog.';
const pattern = /q[a-z]+/g;
const matches = text.match(pattern);
console.log(matches); // ["quick"]
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员禅心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值