打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
11个 杀手级 JavaScript 单行代码
userphoto

2022.10.21 江苏

关注

每个 JS 开发人员都应该使用 javascript one liner 来提高生产力和技能,所以今天我们讨论一些可以在日常开发生活中使用的 one liner。

1. 对数组进行排序

使用 sort 方法对数组进行排序非常简单。

const number = [2,6,3,7,8,4,0];number.sort();// expected output: [0,2,3,4,6,7,8]

2.检查数组中的值

很多时候我们需要检查值是否存在于数组中,借助 include 方法。

const array1 = [1, 2, 3];console.log(array1.includes(2));// expected output: true

3.过滤数组

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array ['exuberant', 'destruction', 'present']

4. 从数组中查找元素

如果你只需要一个元素,但你在数组中获得了很多元素,不要担心 JavaScript 有 find 方法。

const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);// expected output: 12

5. 查找数组中任何元素的索引

要查找数组中元素的索引,您可以简单地使用 indexOf 方法。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison'));// expected output: 1

6. 将数组转换为字符串

const elements = ['Fire', 'Air', 'Water'];console.log(elements.join(', '));// expected output: 'Fire, Air, Water'

7.支票号码是偶数还是奇数

很容易找出给定的数字是偶数还是奇数。

const isEven = num => num % 2 === 0;orconst isEven = num => !(n & 1);

8.删除数组中的所有重复值

删除数组中所有重复值的一种非常简单的方法

const setArray = arr => [...new Set(arr)];const arr = [1,2,3,4,5,1,3,4,5,2,6];setArray(arr);// expected output: [1,2,3,4,5,6]

9. 合并多个数组的不同方式

// merge but don't remove duplicationsconst merge = (a, b) => a.concat(b);orconst merge = (a, b) => [...a, ...b];// merge with remove duplicationsconst merge = (a, b) => [...new Set(a.concat(b))];orconst merge = (a, b) => [...new Set([...a, ...b])];

10. 滚动到页面顶部

有很多方法可以将页面滚动到顶部。

const goToTop = () => window.scrollTo(0,0, 'smooth');orconst scrollToTop = (element) => element.scrollIntoView({behavior: 'smooth', block: 'start'});// scroll to bottom of the pageconst scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight); 

11.复制到剪贴板

在 Web 应用程序中,复制到剪贴板因其对用户的便利性而迅速普及。
const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);

写在最后

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JavaScript数据方法汇总
JavaScript 中的 7 个杀手级单行代码
9个实用的JavaScript开发技巧,你必须知道一下
js和jquery的数组过滤grep()和filter()数组去重去nullundefind
程序员必须掌握的 12 个 JavaScript 技能!
java开发之常用的Javascript对象方法整理分享
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服