JavaScript的使用小方法

199 阅读3分钟

判断当前标签页是否为可视状态

浏览器可以打开很多标签页,下面 👇🏻 的代码段就是判断当前标签页是否是激活的标签页

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();

可选项 (?)

在 JS 中,我们需要经常检查对象的某些属性是否存在,然后才能再处理它,不然会报错。 早期我们可能会这么干:

const toto = { a: { b: { c: 5 } } }
if (!!toto.a && !!toto.a.b && !!toto.a.b.c) {} // toto.a.b.c exist

如果对象嵌套很深,我们这写法就难以阅读,这时可以使用?来简化:

const toto = { a: { b: { c: 1 } } }
//  如果键不存在,返回 `undefined`。
const test = toto.a?.b?.c?.d // undefined

从 Date 对象中获取时间

使用 Date 对象的 .toLocaleString() 方法转换为时间字符串

const timeFromDate = date => date.toLocaleString();
console.log(timeFromDate(new Date(2024, 2, 30, 17, 30, 10))); 
// Result: "2024/3/30 17:30:10"
console.log(timeFromDate(new Date()));
// Result: 返回当前时间

保留指定的小数位

区别于内置的toFixed,这个toFixed不四色五人

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

检查指定元素是否处于聚焦状态

可以使用 document.activeElement 来判断元素是否处于聚焦状态

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: 如果处于焦点状态会返回 True 否则返回 False

检查当前用户是否是苹果设备

可以使用 navigator.platform 判断当前用户是否是苹果设备

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: 是苹果设备会返回 True

平滑的滚动至页面顶部

window.scrollTo() 会滚动至指定的坐标,如果设置坐标为(0,0),就会回到页面顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: 将会滚动至顶部

// 平滑滚动写法
window.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

获取所有参数的平均值、最小值、最大值

可以使用 reduce() 函数来计算所有参数的平均值

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

// 最大值
const array  = [5,4,7,8,9,2];
array.reduce((a,b) => a>b?a:b);
// 输出: 9


// 最小值
const array  = [5,4,7,8,9,2];
array.reduce((a,b) => a<b?a:b);
// 输出: 2



获取url参数

URLSearchParams

// 创建一个URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search);
// 把键值对列表转换为一个对象
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params)

Array(5).full('')

const array = Array(5).fill(''); 
// 输出
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); 
// 输出
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5

打乱数组,数组洗牌

利用内置Math.random()方法。

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

将十进制转换为二进制或十六进制

const num = 10;

num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"

使用解构简单交换两值

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// 输出
(2) [8, 5]

使网站可编辑

document.designMode = "on"

简单转码

function myEncode (x) {
  return window.btoa(encodeURIComponent(x))
}

function myDecode (x) {
  return decodeURIComponent(window.atob(x))
}