本篇文章给大家介绍20+个javascript单行代码,可以帮助你像专业人士一样编写代码。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
javascript不断发展壮大,
因为它是最容易上手的语言之一,因此为市场上的新成为技术怪才打开了大门。(问号脸?)
的确,javascript可以做很多出色的事情!还有很多东西要学习。
而且,无论你是javascript的新手还是更多的专业开发人员,学习新知识总是一件好事。
本文整理了一些非常有用的单行代码(20+),这些单行代码可以帮助你提高工作效率并可以帮助调试代码。
什么是单行代码?
单行代码是一种代码实践,其中我们仅用一行代码执行某些功能。01-随机获取布尔值此函数将使用math.random()方法返回布尔值(真或假)。
math.random创建一个介于0和1之间的随机数,然后我们检查它是否大于或小于0.5。
这意味着有50/50的机会会得到对或错。
const getrandomboolean = () => math.random() >= 0.5;console.log(getrandomboolean());// a 50/50 chance of returning true or false
02-检查日期是否为周末通过此功能,你将能够检查提供的日期是工作日还是周末。
const isweekend = (date) => [0, 6].indexof(date.getday()) !== -1;console.log(isweekend(new date(2021, 4, 14)));// false (friday)console.log(isweekend(new date(2021, 4, 15)));// true (saturday)
03-检查数字是偶数还是奇数简单的实用程序功能,用于检查数字是偶数还是奇数。
const iseven = (num) => num % 2 === 0;console.log(iseven(5));// falseconsole.log(iseven(4));// true
04-获取数组中的唯一值(数组去重)从数组中删除所有重复值的非常简单的方法。此函数将数组转换为set,然后返回数组。
const uniquearr = (arr) => [...new set(arr)];console.log(uniquearr([1, 2, 3, 1, 2, 3, 4, 5]));// [1, 2, 3, 4, 5]
05-检查变量是否为数组一种检查变量是否为数组的干净简便的方法。
当然,也可以有其他方法
const isarray = (arr) => array.isarray(arr);console.log(isarray([1, 2, 3]));// trueconsole.log(isarray({ name: 'ovi' }));// falseconsole.log(isarray('hello world'));// false
06-在两个数字之间生成一个随机数这将以两个数字为参数,并将在这两个数字之间生成一个随机数!
const random = (min, max) => math.floor(math.random() * (max - min + 1) + min);console.log(random(1, 50));// could be anything from 1 - 50
07-生成随机字符串(唯一id?)也许你需要临时的唯一id,这是一个技巧,你可以使用它在旅途中生成随机字符串。
const randomstring = () => math.random().tostring(36).slice(2);console.log(randomstring());// could be anything!!!
08-滚动到页面顶部所述window.scrollto()方法把一个x和y坐标滚动到。
如果将它们设置为零和零,我们将滚动到页面顶部。
const scrolltotop = () => window.scrollto(0, 0);scrolltotop();
09-切换布尔切换布尔值是非常基本的编程问题之一,可以通过许多不同的方法来解决。
代替使用if语句来确定将布尔值设置为哪个值,你可以使用函数使用!翻转当前值。非运算符。
// bool is stored somewhere in the upperscopeconst togglebool = () => (bool = !bool);//orconst togglebool = b => !b;
10-交换两个变量下面的代码是不使用第三个变量而仅使用一行代码即可交换两个变量的更简单方法之一。
[foo, bar] = [bar, foo];
11-计算两个日期之间的天数要计算两个日期之间的天数,
我们首先找到两个日期之间的绝对值,然后将其除以86400000(等于一天中的毫秒数),最后将结果四舍五入并返回。
const daysdiff = (date, date2) => math.ceil(math.abs(date - date2) / 86400000);console.log(daysdiff(new date('2021-05-10'), new date('2021-11-25')));// 199
12-将文字复制到剪贴板ps:你可能需要添加检查以查看是否存在navigator.clipboard.writetext
const copytexttoclipboard = async (text) => { await navigator.clipboard.writetext(text);};
13-合并多个数组的不同方法有两种合并数组的方法。其中之一是使用concat方法。另一个使用扩展运算符(…)。
ps:我们也可以使用“设置”对象从最终数组中复制任何内容。
// merge but don't remove the duplicationsconst merge = (a, b) => a.concat(b);// orconst merge = (a, b) => [...a, ...b];// merge and remove the duplicationsconst merge = [...new set(a.concat(b))];// orconst merge = [...new set([...a, ...b])];
14-获取javascript语言的实际类型人们有时会使用库来查找javascript中某些内容的实际类型,这一小技巧可以节省你的时间(和代码大小)。
const truetypeof = (obj) => { return object.prototype.tostring.call(obj).slice(8, -1).tolowercase();};console.log(truetypeof(''));// stringconsole.log(truetypeof(0));// numberconsole.log(truetypeof());// undefinedconsole.log(truetypeof(null));// nullconsole.log(truetypeof({}));// objectconsole.log(truetypeof([]));// arrayconsole.log(truetypeof(0));// numberconsole.log(truetypeof(() => {}));// function
15-在结尾处截断字符串需要从头开始截断字符串,这不是问题!
const truncatestring = (string, length) => { return string.length < length ? string : `${string.slice(0, length - 3)}...`;};console.log( truncatestring('hi, i should be truncated because i am too loooong!', 36),);// hi, i should be truncated because...
16-从中间截断字符串从中间截断字符串怎么样?
该函数将一个字符串作为第一个参数,然后将我们需要的字符串大小作为第二个参数,然后从第3个和第4个参数开始和结束需要多少个字符
const truncatestringmiddle = (string, length, start, end) => { return `${string.slice(0, start)}...${string.slice(string.length - end)}`;};console.log( truncatestringmiddle( 'a long story goes here but then eventually ends!', // string 25, // 需要的字符串大小 13, // 从原始字符串第几位开始截取 17, // 从原始字符串第几位停止截取 ),);// a long story ... eventually ends!
17-大写字符串好吧,不幸的是,javascript没有内置函数来大写字符串,但是这种解决方法可以实现。
const capitalize = (str) => str.charat(0).touppercase() + str.slice(1);console.log(capitalize('hello world'));// hello world
18-检查当前选项卡是否在视图/焦点内此简单的帮助程序方法根据选项卡是否处于视图/焦点状态而返回true或false
const istabinview = () => !document.hidden; // not hiddenistabinview();// true/false
19-检查用户是否在apple设备上如果用户使用的是apple设备,则返回true
const isappledevice = () => /mac|ipod|iphone|ipad/.test(navigator.platform);console.log(isappledevice);// true/false
20-三元运算符当你只想在一行中编写if..else语句时,这是一个很好的代码保护程序。
// longhandconst age = 18;let greetings;if (age < 18) { greetings = 'you are not old enough';} else { greetings = 'you are young!';}// shorthandconst greetings = age < 18 ? 'you are not old enough' : 'you are young!';
21-短路评估速记在将变量值分配给另一个变量时,可能要确保源变量不为null,未定义或为空。
可以编写带有多个条件的long if语句,也可以使用短路评估。
// longhandif (name !== null || name !== undefined || name !== '') { let fullname = name;}// shorthandconst fullname = name || 'buddy';
希望对你有所帮助!
英文原文地址:https://dev.to/ovi/20-javascript-one-liners-that-will-help-you-code-like-a-pro-4ddc
更多编程相关知识,请访问:编程入门!!
以上就是学会这20+个javascript单行代码,让你像专业人士一样编写代码的详细内容。