一些常用的JavaScript 代码片段

12 阅读1分钟

获取滚动位置

如果已定义,请使用pageXOffset和pageYOffset,否则使用scrollLeft和scrollTop,可以省略el来使用window的默认值。

const getScrollPos = (el = window) =>  
  
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,  
  
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});  
  
// getScrollPos() -> {x: 0, y: 200}

数组平均数

使用reduce()将每个值添加到累加器,初始值为0,总和除以数组长度。

const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;  
  
// average([1,2,3]) -> 2

大写每个单词的首字母

使用replace()匹配每个单词的第一个字符,并使用toUpperCase()来将其大写。

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

// capitalizeEveryWord('hello world!') -> 'Hello World!'`

当前URL

使用window.location.href来获取当前URL。

`const currentUrl = _ => window.location.href;

// currentUrl() -> 'https://google.com'`

从数组中获取最小值

使用Math.min()与spread运算符(…)结合得到数组中的最小值。

const arrayMin = arr => Math.min(...arr);

// arrayMin([10, 1, 5]) -> 1`

## 范围内的随机整数

使用Math.random()生成一个随机值,使用乘法将其映射到所需的范围。

const randomInRange = (min, max) => Math.random() * (max - min) + min;  
  
// randomInRange(2,10) -> 6.0211363285087005

译文链接:juejin.cn/post/684490…

原文链接:codebay.cn/post/7452.h…