17个JavaScript 单行程序

17个JavaScript 单行程序

一、DOM & BOM 相关

1、检查元素是否获得焦点

const hasFocus = (ele) => ele === document.activeElement;


2、获取元素的所有兄弟节点

const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);

// 或者
const siblings = (ele) => [...ele.parentNode.children].filter((child) => child !== ele);


3、获取选定的文本

const getSelectedText = () => window.getSelection().toString();


4、返回上一个页面

history.back();
// 或者
history.go(-1);


5、清除所有 cookie

const clearCookies = () => document.cookie
  .split(";")
  .forEach((c) =>(document.cookie = c.replace(/^ +/, "")
  .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));


6、将 cookie 转换为对象

const cookies = document.cookie
  .split(";")
  .map((item) => item.split("="))
  .reduce((acc, [k, v]) => (acc[k.trim().replace(""", "")] = v) && acc, {});

二、数组相关

7、比较两个数组

// `a` 和 `b` 是一个数组
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// 或者
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

// 示例
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, "2", 3]); // false


8、将对象数组转换为对象

const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// 或者
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));

// 示例
toObject([
  { id: "1", name: "Alpha", gender: "Male" },
  { id: "2", name: "Bravo", gender: "Male" },
  { id: "3", name: "Charlie", gender: "Female" }],
"id");

/*
{
"1": { id: "1", name: "Alpha", gender: "Male" },
"2": { id: "2", name: "Bravo", gender: "Male" },
"3": { id: "3", name: "Charlie", gender: "Female" }
}
*/

9、按对象数组的属性计数

const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});

// 示例
countBy([
{ branch: "audi", model: "q8", year: "2019" },
{ branch: "audi", model: "rs7", year: "2020" },
{ branch: "ford", model: "mustang", year: "2019" },
{ branch: "ford", model: "explorer", year: "2020" },
{ branch: "bmw", model: "x7", year: "2020" },
],
"branch");

// { "audi": 2, "ford": 2, "bmw": 1 }

10、检查数组是否为空

const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;

// 示例
isNotEmpty([]); // false
isNotEmpty([1, 2, 3]); // true

三、对象相关

11、检查多个对象是否相等

const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));

// 示例
isEqual({ foo: "bar" }, { foo: "bar" }); // true
isEqual({ foo: "bar" }, { bar: "foo" }); // false


12、从对象数组中提取属性的值

const pluck = (objs, property) => objs.map((obj) => obj[property]);

// 示例
pluck([
  { name: "John", age: 20 },
  { name: "Smith", age: 25 },
  { name: "Peter", age: 30 },
],
"name");

// ["John", "Smith", "Peter"]

13、反转对象的键和值

const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
// 或者
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));

// 示例
invert({ a: "1", b: "2", c: "3" }); // { 1: "a", 2: "b", 3: "c" }

14、从对象中删除所有空和未定义的属性

const removeNullUndefined = (obj) =>
  Object.entries(obj).reduce(
    (a, [k, v]) => (v == null ? a : ((a[k] = v), a)),
    {},
  );

// 或者
const removeNullUndefined = (obj) =>
  Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

// 或者
const removeNullUndefined = (obj) =>
  Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

// 示例
removeNullUndefined({
  foo: null,
  bar: undefined,
  fuzz: 42
});
// { fuzz: 42 }

15、按属性对对象进行排序

const sort = (obj) =>
  Object.keys(obj)
    .sort()
    .reduce((p, c) => ((p[c] = obj[c]), p), {});

// 示例
const colors = {
  white: "#ffffff",
  black: "#000000",
  red: "#ff0000",
  green: "#008000",
  blue: "#0000ff",
};
sort(colors);
/*
{
  black: "#000000",
  blue: "#0000ff",
  green: "#008000",
  red: "#ff0000",
  white: "#ffffff",
}
*/

16、检查一个对象是否是一个 Promise

const isPromise = (obj) =>
  !!obj &&
  (typeof obj === "object" || typeof obj === "function") &&
  typeof obj.then === "function";


17、检查对象是否为数组

const isArray = (obj) => Array.isArray(obj);

到此这篇关于JavaScript 单行程序 的文章就介绍到这了,更多相关JavaScript 单行程序 内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!