常用js代码片段(二)

29、将输入的数字拆分成单个数字组成的数组。

const digitize = n => [...`${n}`].map(i => parseInt(i));
digitize(431); // [4, 3, 1]

30、计算两点之间的距离

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3); // 2.23606797749979

31、此段代码将给定的数组从左边开始删除 n 个元素

const drop = (arr, n = 1) => arr.slice(n);
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []

32、此段代码将给定的数组从右边开始删除 n 个元素

const dropRight = (arr, n = 1) => arr.slice(0, -n);
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []

33、此段代码将给定的数组按照给定的函数条件从右开始删除,直到当前元素满足函数条件为True时,停止删除,并返回数组剩余元素。

const dropRightWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
  return arr;
};
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]

34、按照给的的函数条件筛选数组,不满足函数条件的将从数组中移除。

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]

35、接收两个DOM元素对象参数,判断后者是否是前者的子元素。

const elementContains = (parent, child) => parent !== child && parent.contains(child);
elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false

36、移除数组中重复的元素

const filterNonUnique = arr => [ …new Set(arr)];
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]

37、按照给定的函数条件,查找第一个满足条件对象的键值。

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
findKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  o => o['active']
); // 'barney'

38、按照给定的函数条件筛选数组,将最后一个满足条件的元素进行删除。

const findLast = (arr, fn) => arr.filter(fn).pop();
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3

39、按照指定数组的深度,将嵌套数组进行展平。

const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

40、按照给定的函数条件,从数组的右边往左依次进行执行。

const forEachRight = (arr, callback) =>
  arr
    .slice(0)
    .reverse()
    .forEach(callback);
forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'

41、此段代码按照给定的函数条件,支持三个参数作为输入(值、键、对象本身),进行迭代对象。

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1

42、此段代码输出函数的名称。

const functionName = fn => (console.debug(fn.name), fn);

functionName(Math.max); // max (logged in debug channel of console)

43、此段代码从Date对象里获取当前时间。

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // "08:38:00"

44、此段代码返回两个日期之间相差多少天。

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);
  
getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2

45、此代码返回DOM元素节点对应的属性值。

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];

getStyle(document.querySelector('p'), 'font-size'); // '16px'

46、此段代码的主要功能就是返回数据的类型。

const getType = v =>
  v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
  
getType(new Set([1, 2, 3])); // 'set'

47、此段代码返回DOM元素是否包含指定的Class样式。

const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true

48、此段代码输出数组的第一个元素。

const head = arr => arr[0];

head([1, 2, 3]); // 1

49、此段代码隐藏指定的DOM元素。

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

hide(document.querySelectorAll('img')); // Hides all <img> elements on the page

50、此段代码的功能就是将http网址重定向https网址。

const httpsRedirect = () => {
  if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};

httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com

51、此代码可以返回数组中某个值对应的所有索引值,如果不包含该值,则返回一个空数组。

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []

52、此段代码返回数组中除最后一个元素的所有元素。

const initial = arr => arr.slice(0, -1);

initial([1, 2, 3]); // [1,2]const initial = arr => arr.slice(0, -1);
initial([1, 2, 3]); // [1,2]

53、此段代码的功能主要是在给定的DOM节点后插入新的节点内容

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);

insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>

54、此段代码的功能主要是在给定的DOM节点前插入新的节点内容

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);

insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>

55、此段代码返回两个数组元素之间的交集。

const intersection = (a, b) => {
  const s = new Set(b);
  return a.filter(x => s.has(x));
};

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

56、按照给定的函数处理需要对比的数组元素,然后根据处理后的数组,找出交集,最后从第一个数组中将对应的元素输出。

const intersectionBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => s.has(fn(x)));
};

intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
原文地址:https://www.cnblogs.com/jmwlhj/p/13297452.html