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 單行程序 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: