8 个最佳的 JavaScript 一行代码技巧

如果你是编程新手,可能既兴奋又有点不知所措对吧?别紧张!🙂现在,我们要看一些非常简单但超酷的JavaScript一行代码技巧。这些代码虽短但功能强大,可以帮你节省时间并让你的朋友们眼前一亮。让我们一起来探索神奇的JavaScript简单技巧的世界吧!

1. 在一个数组中随机取一个元素

// Input: [1, 2, 3, 4]
const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];
// Output: Something like 2, or 4, or 1...you get it.

2. 避免数组中的重复元素

// Input: [1, 2, 2, 3]
const uniqueArray = [...new Set([1, 2, 2, 3])];
// Output: [1, 2, 3]

3. 将数组按照某个属性排序

// Input: 'name', [{name:'Bob', age:25}, {name:'Alice', age:22}]
const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
// Output: [{name:'Alice', age:22}, {name:'Bob', age:25}]

4. 判断两个对象或数组是否相等

// Input: [1, 2], [1, 2]
const arraysEqual = JSON.stringify([1, 2]) === JSON.stringify([1, 2]);
// Output: true

5. 让你的代码等待某一固定时间

const chill = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
  console.log("Before waiting");
  await chill(2000);
  console.log("After waiting for 2 seconds");
})();

6. 取出数组中某个对象的某一属性

const pluck = (arr, key) => arr.map(obj => obj[key]);
console.log(pluck([{x: 1}, {x: 2}], 'x')); // Output: [1, 2]

7. 在数组的某个特定位置插入一个数据

// Input: [1, 2, 4]
const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem),a);
// Output: [1, 2, 3, 4]

8. 随机生成一个颜色

// Input: No input needed
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0);
// Output: Something like #f5a623

哇,真刺激!🎢我们刚刚介绍了8个简单但方便的JavaScript快捷键。这些一行代码就像小工具包🛠️,可以帮助你轻松完成很酷的功能。你是否也学到了一些很酷的快捷键或技巧,想分享给大家?我们非常期待!请在下面的评论区留言。祝编码愉快,记住,最好的代码是让你会心一笑的代码!😊

祝编码愉快,记住,要永远保持优雅和幽默!🍸🎉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值