36涓伐浣滀腑甯哥敤鐨凧avaScript鍑芥暟鐗囨

Posted wscats

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了36涓伐浣滀腑甯哥敤鐨凧avaScript鍑芥暟鐗囨相关的知识,希望对你有一定的参考价值。

濡傛灉鏂囩珷鍜岀瑪璁拌兘甯︽偍涓€涓濆府鍔╂垨鑰呭惎鍙戯紝璇蜂笉瑕佸悵鍟綘鐨勮禐鍜屾敹钘忥紝浣犵殑鑲畾鏄垜鍓嶈繘鐨勬渶澶у姩鍔涴煒?/p>

  • 闄勭瑪璁伴摼鎺ワ紝闃呰寰€鏈熸洿澶氫紭璐ㄦ枃绔犲彲绉绘鏌ョ湅锛屽枩娆㈢殑鍙互缁欐垜鐐硅禐榧撳姳鍝︼細https://github.com/Wscats/CV/issues/32

鏁扮粍 Array

鏁扮粍鍘婚噸

function noRepeat(arr) {
  return [...new Set(arr)];
}

鏌ユ壘鏁扮粍鏈€澶?/h2>
function arrayMax(arr) {
  return Math.max(...arr);
}

鏌ユ壘鏁扮粍鏈€灏?/h2>
function arrayMin(arr) {
  return Math.min(...arr);
}

杩斿洖宸?size 涓洪暱搴︾殑鏁扮粍鍒嗗壊鐨勫師鏁扮粍

function chunk(arr, size = 1) {
  return Array.from(
    {
      length: Math.ceil(arr.length / size),
    },
    (v, i) => arr.slice(i * size, i * size + size)
  );
}

妫€鏌ユ暟缁勪腑鏌愬厓绱犲嚭鐜扮殑娆℃暟

function countOccurrences(arr, value) {
  return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
}

鎵佸钩鍖栨暟缁?/h2>
  • 榛樿 depth 鍏ㄩ儴灞曞紑
function flatten(arr, depth = -1) {
  if (depth === -1) {
    return [].concat(
      ...arr.map((v) => (Array.isArray(v) ? this.flatten(v) : v))
    );
  }
  if (depth === 1) {
    return arr.reduce((a, v) => a.concat(v), []);
  }
  return arr.reduce(
    (a, v) => a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v),
    []
  );
}

瀵规瘮涓や釜鏁扮粍骞朵笖杩斿洖鍏朵腑涓嶅悓鐨勫厓绱?/h2>
function diffrence(arrA, arrB) {
  return arrA.filter((v) => !arrB.includes(v));
}

杩斿洖涓や釜鏁扮粍涓浉鍚岀殑鍏冪礌

function intersection(arr1, arr2) {
  return arr2.filter((v) => arr1.includes(v));
}

浠庡彸鍒犻櫎 n 涓厓绱?/h2>
function dropRight(arr, n = 0) {
  return n < arr.length ? arr.slice(0, arr.length - n) : [];
}

鎴彇绗竴涓鍚堟潯浠剁殑鍏冪礌鍙婂叾浠ュ悗鐨勫厓绱?/h2>
function dropElements(arr, fn) {
  while (arr.length && !fn(arr[0])) arr = arr.slice(1);
  return arr;
}

杩斿洖鏁扮粍涓笅鏍囬棿闅?nth 鐨勫厓绱?/h2>
function everyNth(arr, nth) {
  return arr.filter((v, i) => i % nth === nth - 1);
}

杩斿洖鏁扮粍涓 n 涓厓绱?/h2>
  • 鏀寔璐熸暟
function nthElement(arr, n = 0) {
  return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}

杩斿洖鏁扮粍澶村厓绱?/h2>
function head(arr) {
  return arr[0];
}

杩斿洖鏁扮粍鏈熬鍏冪礌

function last(arr) {
  return arr[arr.length - 1];
}

鏁扮粍涔辨帓

function shuffle(arr) {
  let array = arr;
  let index = array.length;

  while (index) {
    index -= 1;
    let randomInedx = Math.floor(Math.random() * index);
    let middleware = array[index];
    array[index] = array[randomInedx];
    array[randomInedx] = middleware;
  }

  return array;
}

娴忚鍣ㄥ璞?BOM

鍒よ娴忚鍣ㄦ槸鍚︽敮鎸?CSS 灞炴€?/h2>
/**
 * 鍛婄煡娴忚鍣ㄦ敮鎸佺殑鎸囧畾css灞炴€ф儏鍐? * @param {String} key - css灞炴€э紝鏄睘鎬х殑鍚嶅瓧锛屼笉闇€瑕佸姞鍓嶇紑
 * @returns {String} - 鏀寔鐨勫睘鎬ф儏鍐? */
function validateCssKey(key) {
  const jsKey = toCamelCase(key); // 鏈変簺css灞炴€ф槸杩炲瓧绗﹀彿褰㈡垚
  if (jsKey in document.documentElement.style) {
    return key;
  }
  let validKey = "";
  // 灞炴€у悕涓哄墠缂€鍦╦s涓殑褰㈠紡锛屽睘鎬у€兼槸鍓嶇紑鍦╟ss涓殑褰㈠紡
  // 缁忓皾璇曪紝Webkit 涔熷彲鏄瀛楁瘝灏忓啓 webkit
  const prefixMap = {
    Webkit: "-webkit-",
    Moz: "-moz-",
    ms: "-ms-",
    O: "-o-",
  };
  for (const jsPrefix in prefixMap) {
    const styleKey = toCamelCase(`${jsPrefix}-${jsKey}`);
    if (styleKey in document.documentElement.style) {
      validKey = prefixMap[jsPrefix] + key;
      break;
    }
  }
  return validKey;
}

/**
 * 鎶婃湁杩炲瓧绗﹀彿鐨勫瓧绗︿覆杞寲涓洪┘宄板懡鍚嶆硶鐨勫瓧绗︿覆
 */
function toCamelCase(value) {
  return value.replace(/-(\\w)/g, (matched, letter) => {
    return letter.toUpperCase();
  });
}

/**
 * 妫€鏌ユ祻瑙堝櫒鏄惁鏀寔鏌愪釜css灞炴€у€硷紙es6鐗堬級
 * @param {String} key - 妫€鏌ョ殑灞炴€у€兼墍灞炵殑css灞炴€у悕
 * @param {String} value - 瑕佹鏌ョ殑css灞炴€у€硷紙涓嶈甯﹀墠缂€锛? * @returns {String} - 杩斿洖娴忚鍣ㄦ敮鎸佺殑灞炴€у€? */
function valiateCssValue(key, value) {
  const prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
  const prefixValue = prefix.map((item) => {
    return item + value;
  });
  const element = document.createElement("div");
  const eleStyle = element.style;
  // 搴旂敤姣忎釜鍓嶇紑鐨勬儏鍐碉紝涓旀渶鍚庝篃瑕佸簲鐢ㄤ笂娌℃湁鍓嶇紑鐨勬儏鍐碉紝鐪嬫渶鍚庢祻瑙堝櫒璧锋晥鐨勪綍绉嶆儏鍐?  // 杩欏氨鏄渶濂藉湪prefix閲岀殑鏈€鍚庝竴涓厓绱犳槸\'\'
  prefixValue.forEach((item) => {
    eleStyle[key] = item;
  });
  return eleStyle[key];
}

/**
 * 妫€鏌ユ祻瑙堝櫒鏄惁鏀寔鏌愪釜css灞炴€у€? * @param {String} key - 妫€鏌ョ殑灞炴€у€兼墍灞炵殑css灞炴€у悕
 * @param {String} value - 瑕佹鏌ョ殑css灞炴€у€硷紙涓嶈甯﹀墠缂€锛? * @returns {String} - 杩斿洖娴忚鍣ㄦ敮鎸佺殑灞炴€у€? */
function valiateCssValue(key, value) {
  var prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
  var prefixValue = [];
  for (var i = 0; i < prefix.length; i++) {
    prefixValue.push(prefix[i] + value);
  }
  var element = document.createElement("div");
  var eleStyle = element.style;
  for (var j = 0; j < prefixValue.length; j++) {
    eleStyle[key] = prefixValue[j];
  }
  return eleStyle[key];
}

function validCss(key, value) {
  const validCss = validateCssKey(key);
  if (validCss) {
    return validCss;
  }
  return valiateCssValue(key, value);
}
  • 鎽樿嚜 https://juejin.im/post/5e58f398f265da574a1eb569

杩斿洖褰撳墠缃戦〉鍦板潃

function currentURL() {
  return window.location.href;
}

鑾峰彇婊氬姩鏉′綅缃?/h2>
function getScrollPosition(el = window) {
  return {
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
  };
}

鑾峰彇 url 涓殑鍙傛暟

function getURLParameters(url) {
  return url
    .match(/([^?=&]+)(=([^&]*))/g)
    .reduce(
      (a, v) => (
        (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
      ),
      {}
    );
}

椤甸潰璺宠浆锛屾槸鍚﹁褰曞湪 history 涓?/h2>
function redirect(url, asLink = true) {
  asLink ? (window.location.href = url) : window.location.replace(url);
}

婊氬姩鏉″洖鍒伴《閮ㄥ姩鐢?/h2>
function scrollToTop() {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  } else {
    window.cancelAnimationFrame(scrollToTop);
  }
}

澶嶅埗鏂囨湰

function copy(str) {
  const el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly", "");
  el.style.position = "absolute";
  el.style.left = "-9999px";
  el.style.top = "-9999px";
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0
      ? document.getSelection().getRangeAt(0)
      : false;
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
}

妫€娴嬭澶囩被鍨?/h2>
function detectDeviceType() {
  return /android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";
}

Cookie

澧?/h2>
function setCookie(key, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    key +
    "=" +
    escape(value) +
    (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}

鍒?/h2>
function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null) {
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  }
}

鏌?/h2>
function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) {
    return arr[2];
  } else {
    return null;
  }
}

鏃ユ湡 Date

鏃堕棿鎴宠浆鎹负鏃堕棿

  • 榛樿涓哄綋鍓嶆椂闂磋浆鎹㈢粨鏋?/li>
  • isMs 涓烘椂闂存埑鏄惁涓烘绉?/li>
function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) {
  const date = new Date(timestamp * (isMs ? 1 : 1000));
  return `${date.getFullYear()}-${
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

聽 鏂囨。瀵硅薄 DOM

鍥哄畾婊氬姩鏉?/h2>
/**
 * 鍔熻兘鎻忚堪锛氫竴浜涗笟鍔″満鏅紝濡傚脊妗嗗嚭鐜版椂锛岄渶瑕佺姝㈤〉闈㈡粴鍔紝杩欐槸鍏煎瀹夊崜鍜?ios 绂佹椤甸潰婊氬姩鐨勮В鍐虫柟妗? */

let scrollTop = 0;

function preventScroll() {
  // 瀛樺偍褰撳墠婊氬姩浣嶇疆
  scrollTop = window.scrollY;

  // 灏嗗彲婊氬姩鍖哄煙鍥哄畾瀹氫綅锛屽彲婊氬姩鍖哄煙楂樺害涓?0 鍚庡氨涓嶈兘婊氬姩浜?  document.body.style["overflow-y"] = "hidden";
  document.body.style.position = "fixed";
  document.body.style.width = "100%";
  document.body.style.top = -scrollTop + "px";
  // document.body.style[\'overscroll-behavior\'] = \'none\'
}

function recoverScroll() {
  document.body.style["overflow-y"] = "auto";
  document.body.style.position = "static";
  // document.querySelector(\'body\').style[\'overscroll-behavior\'] = \'none\'

  window.scrollTo(0, scrollTop);
}

鍒ゆ柇褰撳墠浣嶇疆鏄惁涓洪〉闈㈠簳閮?/h2>
  • 杩斿洖鍊间负 true/false
function bottomVisible() {
  return (
    document.documentElement.clientHeight + window.scrollY >=
    (document.documentElement.scrollHeight ||
      document.documentElement.clientHeight)
  );
}

鍒ゆ柇鍏冪礌鏄惁鍦ㄥ彲瑙嗚寖鍥村唴

  • partiallyVisible 涓烘槸鍚︿负瀹屽叏鍙
function elementIsVisibleInViewport(el, partiallyVisible = false) {
  const { top, left, bottom, right } = el.getBoundingClientRect();

  return partiallyVisible
    ? ((top > 0 && top < innerHeight) ||
        (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}

鑾峰彇鍏冪礌 css 鏍峰紡

function getStyle(el, ruleName) {
  return getComputedStyle(el, null).getPropertyValue(ruleName);
}

杩涘叆鍏ㄥ睆

function launchFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
}

launchFullscreen(document.documentElement);
launchFullscreen(document.getElementById("id")); //鏌愪釜鍏冪礌杩涘叆鍏ㄥ睆

閫€鍑哄叏灞?/h2>
function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}

exitFullscreen();

鍏ㄥ睆浜嬩欢

document.addEventListener("fullscreenchange", function (e) {
  if (document.fullscreenElement) {
    console.log("杩涘叆鍏ㄥ睆");
  } else {
    console.log("閫€鍑哄叏灞?);
  }
});

鏁板瓧 Number

鏁板瓧鍗冨垎浣嶅垎鍓?/h2>
function commafy(num) {
  return num.toString().indexOf(".") !== -1
    ? num.toLocaleString()
    : num.toString().replace(/(\\d)(?=(?:\\d{3})+$)/g, "$1,");
}

鐢熸垚闅忔満鏁?/h2>
function randomNum(min, max) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * min + 1, 10);
    case 2:
      return parseInt(Math.random() * (max - min + 1) + min, 10);
    default:
      return 0;
  }
}

浜ゆ祦

鏂囩珷鍚屾鎸佺画鏇存柊锛屽線鏈熸枃绔犳敹褰曞湪https://github.com/Wscats/art...
娆㈣繋鎮ㄧ殑鍏虫敞鍜屼氦娴侌煒?/p>

以上是关于36涓伐浣滀腑甯哥敤鐨凧avaScript鍑芥暟鐗囨的主要内容,如果未能解决你的问题,请参考以下文章

part4-2 娴佺▼鎺у埗浜岋紙寰幆缁撴瀯锛寃hile銆乫or寰幆锛屽垪琛ㄦ帹瀵煎紡銆佺敓鎴愬櫒鎺ㄥ寮忥紝甯哥敤宸ュ叿鍑芥暟锛屾帶鍒跺惊鐜粨鏋勶紝4涓畝鍗曞疄渚嬶級

DevOps 浼氳浣犲け涓氬悧锛?| Linux 涓浗

鍦ㄥ伐浣滀腑浣犲彲鑳戒細閬囪鐨勪簨鎯呭搱

SUMSQ鍑芥暟璁$畻鏁板€煎钩鏂瑰拰

鍑芥暟寮忕紪绋嬩腑鐨勫壇浣滅敤姒傚康