269個JavaScript工具函數,助你提高工做效率(9)

269個JavaScript工具函數,助你提高工做效率.png

241.返回數組中第 n 個元素(支持負數)

方案一:slice

function nthElement(arr, n = 0) {
  return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}
nthElement([1,2,3,4,5], 0)
nthElement([1,2,3,4,5], -1)
複製代碼

方案二:三目運算符

function nthElement(arr, n = 0) {
  return (n >= 0 ? arr[0] : arr[arr.length + n])
}
nthElement([1,2,3,4,5], 0)
nthElement([1,2,3,4,5], -1)
複製代碼

242.返回數組頭元素

方案一:

function head(arr) {
  return arr[0];
}
head([1,2,3,4])
複製代碼

方案二:

function head(arr) {
  return arr.slice(0,1)[0];
}
head([1,2,3,4])
複製代碼

243.返回數組末尾元素

方案一:

function last(arr) {
  return arr[arr.length - 1];
}
複製代碼

方案二:

function last(arr) {
  return arr.slice(-1)[0];
}
last([1,2,3,4,5])
複製代碼

245.數組亂排

方案一:洗牌算法

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;
}
shuffle([1,2,3,4,5])
複製代碼

方案二:sort + random

function shuffle(arr) {
  return arr.sort((n,m)=>Math.random() - .5)
}
shuffle([1,2,3,4,5])
複製代碼

246.僞數組轉換爲數組

方案一:Array.from

Array.from({length: 2})
複製代碼

方案二:prototype.slice

Array.prototype.slice.call({length: 2,1:1})
複製代碼

方案三:prototype.splice

Array.prototype.splice.call({length: 2,1:1},0)
複製代碼

瀏覽器對象 BOM

195.判讀瀏覽器是否支持 CSS 屬性

/**
 * 告知瀏覽器支持的指定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 = "";
  // 屬性名爲前綴在js中的形式,屬性值是前綴在css中的形式
  // 經嘗試,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);
}
複製代碼

segmentfault.com/a/11… 它裏面有 forEach。css

247.返回當前網頁地址

方案一:location

function currentURL() {
  return window.location.href;
}
currentURL()
複製代碼

方案二:a 標籤

function currentURL() {
  var el = document.createElement('a')
  el.href = ''
  return el.href
}
currentURL()
複製代碼

獲取滾動條位置

function getScrollPosition(el = window) {
  return {
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
  };
}
複製代碼

248.獲取 url 中的參數

方案一:正則 + reduce

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

方案二:split + reduce

function getURLParameters(url) {
  return url
    .split('?') //取?分割
    .slice(1) //不要第一部分
    .join() //拼接
    .split('&')//&分割
    .map(v=>v.split('=')) //=分割
    .reduce((s,n)=>{s[n[0]] = n[1];return s},{})
}
getURLParameters(location.href)
// getURLParameters('')
複製代碼

方案三: URLSearchParams

249.頁面跳轉,是否記錄在 history 中

方案一:

function redirect(url, asLink = true) {
  asLink ? (window.location.href = url) : window.location.replace(url);
}
複製代碼

方案二:

function redirect(url, asLink = true) {
  asLink ? window.location.assign(url) : window.location.replace(url);
}
複製代碼

250.滾動條回到頂部動畫

方案一: c - c / 8

c 沒有定義html

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);
  }
}
scrollToTop()
複製代碼

修正以後es6

function scrollToTop() {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, scrollTop - scrollTop / 8);
  } else {
    window.cancelAnimationFrame(scrollToTop);
  }
}
scrollToTop()
複製代碼

251.複製文本

方案一:

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);
  }
}
複製代碼

方案二:cliboard.js

252.檢測設備類型

方案一: ua

function detectDeviceType() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";
}
detectDeviceType()
複製代碼

方案二:事件屬性

function detectDeviceType() {
  return ("ontouchstart" in window || navigator.msMaxTouchPoints)
    ? "Mobile"
    : "Desktop";
}
detectDeviceType()
複製代碼

253.Cookie

function setCookie(key, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    key +
    "=" +
    escape(value) +
    (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}
複製代碼

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();
  }
}
複製代碼

function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) {
    return arr[2];
  } else {
    return null;
  }
}
複製代碼

清空

有時候咱們想清空,可是又沒法獲取到全部的cookie。 這個時候咱們能夠了利用寫滿,而後再清空的辦法。web

日期 Date

254.時間戳轉換爲時間

  • 默認爲當前時間轉換結果
  • isMs 爲時間戳是否爲毫秒
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()}`;
}
複製代碼
  1. 補位能夠改爲 padStart
  2. 補位還能夠改爲 slice

若是作海外的話,還會有時區問題,通常我用moment解決。若是想看原生的算法

獲取當前時間戳

基於上一個想到的問題segmentfault

方案一:Date.parse(new Date())

方案二:Date.now()

方案三:+new Date()

文檔對象 DOM

255固定滾動條

/**
 * 功能描述:一些業務場景,如彈框出現時,須要禁止頁面滾動,這是兼容安卓和 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);
}
複製代碼

256 判斷當前位置是否爲頁面底部

  • 返回值爲 true/false
function bottomVisible() {
  return (
    document.documentElement.clientHeight + window.scrollY >=
    (document.documentElement.scrollHeight ||
      document.documentElement.clientHeight)
  );
}
複製代碼

257判斷元素是否在可視範圍內

  • 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;
}
複製代碼

258.獲取元素 css 樣式

function getStyle(el, ruleName) {
  return getComputedStyle(el, null).getPropertyValue(ruleName);
}
複製代碼

259.進入全屏

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")); //某個元素進入全屏
複製代碼

260退出全屏

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();
複製代碼

261全屏事件

document.addEventListener("fullscreenchange", function (e) {
  if (document.fullscreenElement) {
    console.log("進入全屏");
  } else {
    console.log("退出全屏");
  }
});
複製代碼

數字 Number

262.數字千分位分割

function commafy(num) {
  return num.toString().indexOf(".") !== -1
    ? num.toLocaleString()
    : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
}
commafy(1000)
複製代碼

263.生成隨機數

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;
  }
}
randomNum(1,10)
複製代碼

264 時間戳轉時間

/* 時間戳轉時間 */
function timestampToTime(cjsj) {
	var date = new Date(cjsj); //時間戳爲10位需*1000,時間戳爲13位的話不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
	return Y + M + D
}
複製代碼

265 過濾富文本和空格爲純文本

/* 過濾富文本和空格爲純文本 */
function filterHtml(str) {
	return str.replace(/<[^<>]+>/g, '').replace(/&nbsp;/ig, '');
}
複製代碼

266 指定顯示的文字數量多餘的使用省略號代替

/*指定顯示的文字數量多餘的使用省略號代替*/
function strEllp(str, num = str.length) {
	var subStr = str.substring(0, num);
	return subStr + (str.length > num ? '...' : '');
}
複製代碼

267 獲取滾動條當前的位置

// 獲取滾動條當前的位置
function getScrollTop() {
	var scrollTop = 0
	if (document.documentElement && document.documentElement.scrollTop) {
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body) {
		scrollTop = document.body.scrollTop;
	}
	return scrollTop
}
複製代碼

268 獲取當前可視範圍的高度

// 獲取當前可視範圍的高度
function getClientHeight() {
	var clientHeight = 0
	if (document.body.clientHeight && document.documentElement.clientHeight) {
		clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
	} else {
		clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
	}
	return clientHeight
}
複製代碼

269 獲取文檔完整的高度

// 獲取文檔完整的高度
function getScrollHeight() {
	return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
相關文章
相關標籤/搜索