一行 JavaScript 代码搞定这些操作!

478次阅读  |  发布于3年以前

JavaScript 是一门神奇的语言,它的某些特性让人捉摸不透,但其简洁和灵活性也让人爱不释手。有些功能逻辑按常规思路可能需要不少代码,但是利用某些 API 和语法特性,短短一行代码就能完成!本文简单列举一些常用的一行代码,希望对你有用。

  1. 获取随机布尔值 (true/false)

Math.random()会返回 01之间随机的数字,因此可以利用返回值是否比 0.5小来返回随机的布尔值。

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
  1. 反转字符串

结合数组的反转方法,可以反转字符串:

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// Result: 'dlrow olleh'
  1. 数组去重

面试常考题,偷懒的做法就是用Set

let removeDuplicates = arr => [...new Set(arr)];
console.log(removeDuplicates(['foo', 'bar', 'bar', 'foo', 'bar']));
 // ['foo', 'bar']
  1. 判断浏览器 Tab 窗口是否为活动窗口

利用document.hidden属性可以判断浏览器窗口是否可见(当前活动窗口)。

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
  1. 判断数字奇偶

小学数学题,用% 2判断就行:

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
  1. 获取日期对象的时间部分

日期对象的 .toTimeString()方法可以获取时间格式的字符串,截取前面部分就可以了:

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
console.log(timeFromDate(new Date()));
// Result: will log the current time
  1. 数字截断小数位

如果需要截断浮点数的小数位(不是四舍五入),可以借助 Math.pow() 实现:

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1);       // 25.1
toFixed(25.198726354, 2);       // 25.19
toFixed(25.198726354, 3);       // 25.198
toFixed(25.198726354, 4);       // 25.1987
toFixed(25.198726354, 5);       // 25.19872
toFixed(25.198726354, 6);       // 25.198726
  1. 判断 DOM 元素是否已获得焦点

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
  1. 判断当前环境是否支持 touch 事件

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
  1. 判断是否为 Apple 设备

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
  1. 滚动到页面顶部

window.scrollTo() 方法接受xy坐标参数,用于指定滚动目标位置。全都设置为 0,可以回到页面顶部。注意:IE 不支持 .scrollTo()方法

const goToTop = () => window.scrollTo(0, 0);
goToTop();
  1. 求平均值

reduce的典型应用场景:数组求和。

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8