11个实用JavaScript单行代码

场景:

JavaScript是一门简单而复杂的语言,简单是因为他有很多框架库可以使用,复杂也是因为它有太多的框架库可以选择。这篇文章,想与大家分享11个实用的 JavaScript 单行代码技巧,使用这些javascript单行技巧,可以帮助我们提高生产力和技能。


1.排序数组

使用 sort 方法对数组进行排序非常容易。


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

2.检查数组中的值

很多时候我们需要在 includes 方法的帮助下检查值是否存在于数组中。


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;
or
const isEven = num => !(n & 1);

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

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


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 duplications
const merge = (a, b) => a.concat(b);
or 
const merge = (a, b) => [...a, ...b];// merge with remove duplications
const merge = (a, b) => [...new Set(a.concat(b))];
or 
const merge = (a, b) => [...new Set([...a, ...b])];

10.滚动到页面顶部

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


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

11.复制到剪贴板

在web应用程序中,复制到剪贴板因其对用户的便利性而迅速流行起来。


const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值