欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

盤點(diǎn)30個(gè)經(jīng)典常用的JavaScript知識(shí)點(diǎn)

 更新時(shí)間:2023年04月07日 10:32:01   作者:碼農(nóng)鍵盤上的夢  
這篇文章主要介紹了盤點(diǎn)30個(gè)經(jīng)典常用的JavaScript知識(shí)點(diǎn),為大家總結(jié)一篇日常經(jīng)常使用可能還不知道的點(diǎn),需要的朋友可以參考下

引言:

最近重溫了一遍紅寶書,發(fā)現(xiàn)一些比較好玩的寫法,很多東西日常都在用,但是發(fā)現(xiàn)還會(huì)有不一樣的寫法,結(jié)合一些日常工作中使用的方法,為大家總結(jié)一篇日常經(jīng)常使用可能還不知道的點(diǎn),希望對(duì)你能有所幫助:

一行代碼完成結(jié)構(gòu)加賦值

我們?nèi)粘=?jīng)常使用結(jié)構(gòu)賦值,一般都是先結(jié)構(gòu),再賦值,當(dāng)然我們也可以一行就完成解構(gòu)加賦值操作,看起來非常簡化,當(dāng)然可讀性你懂得!

let people = { name: null, age: null };
let result = { name: '張三',  age: 16 };
 
({ name: people.name, age: people.age} = result);
console.log(people) // {"name":"張三","age":16}###

對(duì)基礎(chǔ)數(shù)據(jù)類型進(jìn)行解構(gòu)

日常中我們應(yīng)該用不到這樣的場景,但是實(shí)際上我們也可以對(duì)基礎(chǔ)數(shù)據(jù)類型解構(gòu)

const {length : a} = '1234';
console.log(a) // 4

對(duì)數(shù)組解構(gòu)快速拿到最后一項(xiàng)值

實(shí)際上我們是可以對(duì)數(shù)組解構(gòu)賦值拿到length屬性的,通過這個(gè)特性也可以做更多的事情。

const arr = [1, 2, 3];
const { 0: first, length, [length - 1]: last } = arr;
first; // 1
last; // 3
length; // 3

將下標(biāo)轉(zhuǎn)為中文零一二三...

日常可能有的列表我們需要將對(duì)應(yīng)的012345轉(zhuǎn)為中文的一、二、三、四、五...,在老的項(xiàng)目看到還有通過自己手動(dòng)定義很多行這樣的寫法,于是寫了一個(gè)這樣的方法轉(zhuǎn)換

export function transfromNumber(number){
  const  INDEX_MAP = ['零','一'.....]
  if(!number) return
  if(number === 10) return INDEX_MAP[number]
  return [...number.toString()].reduce( (pre, cur) => pre  + INDEX_MAP[cur] , '' )
}

判斷整數(shù)的不同方法

/* 1.任何整數(shù)都會(huì)被1整除,即余數(shù)是0。利用這個(gè)規(guī)則來判斷是否是整數(shù)。但是對(duì)字符串不準(zhǔn)確 */
function isInteger(obj) {
 return obj%1 === 0
}
 
/* 1. 添加一個(gè)是數(shù)字的判斷 */
function isInteger(obj) {
 return typeof obj === 'number' && obj%1 === 0
}
 
/* 2. 使用Math.round、Math.ceil、Math.floor判斷 整數(shù)取整后還是等于自己。利用這個(gè)特性來判斷是否是整數(shù)*/
function isInteger(obj) {
 return Math.floor(obj) === obj
}
 
/* 3. 通過parseInt判斷 某些場景不準(zhǔn)確 */
function isInteger(obj) {
 return parseInt(obj, 10) === obj
}
 
/* 4. 通過位運(yùn)算符*/
function isInteger(obj) {
 return (obj | 0) === obj
}

通過css檢測系統(tǒng)的主題色從而全局修改樣式

@media的屬性prefers-color-scheme就可以知道當(dāng)前的系統(tǒng)主題,當(dāng)然使用前需要查查兼容性

@media (prefers-color-scheme: dark) { //... } 
@media (prefers-color-scheme: light) { //... }

javascript也可以輕松做到

window.addEventListener('theme-mode', event =>{ 
    if(event.mode == 'dark'){}
   if(event.mode == 'light'){} 
})
 
window.matchMedia('(prefers-color-scheme: dark)') .addEventListener('change', event => { 
    if (event.matches) {} // dark mode
})

數(shù)組隨機(jī)打亂順序

通過0.5-Math.random()得到一個(gè)隨機(jī)數(shù),再通過兩次sort排序打亂的更徹底,但是這個(gè)方法實(shí)際上并不夠隨機(jī),如果是企業(yè)級(jí)運(yùn)用,建議使用第二種洗牌算法

shuffle(arr) {
      return arr.sort(() => 0.5 - Math.random()). sort(() => 0.5 - Math.random());
 },
function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1))
    ;[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]
  }
  return arr
}

隨機(jī)獲取一個(gè)Boolean值

和上個(gè)原理相同,通過隨機(jī)數(shù)獲取,Math.random()的區(qū)間是0-0.99,用0.5在中間百分之五十的概率

function randomBool() {
    return 0.5 - Math.random()
}

把數(shù)組最后一項(xiàng)移到第一項(xiàng)

function (arr){
    return arr.push(arr.shift());
}

把數(shù)組的第一項(xiàng)放到最后一項(xiàng)

function(arr){
  return arr.unshift(arr.pop());
}

利用set數(shù)組去重

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

dom節(jié)點(diǎn)平滑滾動(dòng)到可是區(qū)域,頂部,底部

原生的scrollTo方法沒有動(dòng)畫,類似于錨點(diǎn)跳轉(zhuǎn),比較生硬,可以通過這個(gè)方法會(huì)自帶平滑的過度效果

function scrollTo(element) {
    element.scrollIntoView({ behavior: "smooth", block: "start" }) // 頂部
    element.scrollIntoView({ behavior: "smooth", block: "end" }) // 底部
    element.scrollIntoView({ behavior: "smooth"}) // 可視區(qū)域
}

獲取隨機(jī)顏色

日常我們經(jīng)常會(huì)需要獲取一個(gè)隨機(jī)顏色,通過隨機(jī)數(shù)即可完成

function getRandomColor(){
    return `#${Math.floor(Math.random() * 0xffffff) .toString(16)}`;
}

檢測是否為空對(duì)象

通過使用Es6的Reflect靜態(tài)方法判斷他的長度就可以判斷是否是空數(shù)組了,也可以通過Object.keys()來判斷

function isEmpty(obj){
    return  Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
}

Boolean轉(zhuǎn)換

一些場景下我們會(huì)將boolean值定義為場景,但是在js中非空的字符串都會(huì)被認(rèn)為是true

function toBoolean(value, truthyValues = ['true']){
  const normalizedValue = String(value).toLowerCase().trim();
  return truthyValues.includes(normalizedValue);
}
toBoolean('TRUE'); // true
toBoolean('FALSE'); // false
toBoolean('YES', ['yes']); // true

各種數(shù)組克隆方法

數(shù)組克隆的方法其實(shí)特別多了,看看有沒有你沒見過的!

const clone = (arr) => arr.slice(0);
const clone = (arr) => [...arr];
const clone = (arr) => Array.from(arr);
const clone = (arr) => arr.map((x) => x);
const clone = (arr) => JSON.parse(JSON.stringify(arr));
const clone = (arr) => arr.concat([]);
const clone = (arr) => structuredClone(arr);

比較兩個(gè)時(shí)間大小

通過調(diào)用getTime獲取時(shí)間戳比較就可以了

function compare(a, b){
    return a.getTime() > b.getTime();
}

計(jì)算兩個(gè)時(shí)間之間的月份差異

function monthDiff(startDate, endDate){
    return  Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
}

一步從時(shí)間中提取年月日時(shí)分秒

時(shí)間格式化輕松解決,一步獲取到年月日時(shí)分秒毫秒,由于toISOString會(huì)丟失時(shí)區(qū),導(dǎo)致時(shí)間差八小時(shí),所以在格式化之前我們加上八個(gè)小時(shí)時(shí)間即可

function extract(date){
   const d = new Date(new Date(date).getTime() + 8*3600*1000);
  return new Date(d).toISOString().split(/[^0-9]/).slice(0, -1);
}
console.log(extract(new Date())) // ['2022', '09', '19', '18', '06', '11', '187']

判斷一個(gè)參數(shù)是不是函數(shù)

有時(shí)候我們的方法需要傳入一個(gè)函數(shù)回調(diào),但是需要檢測其類型,我們可以通過Object的原型方法去檢測,當(dāng)然這個(gè)方法可以準(zhǔn)確檢測任何類型。

function isFunction(v){
   return ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));
}

計(jì)算兩個(gè)坐標(biāo)之間的距離

function distance(p1, p2){
    return `Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}

檢測兩個(gè)dom節(jié)點(diǎn)是否覆蓋重疊

有些場景下我們需要判斷dom是否發(fā)生碰撞了或者重疊了,我們可以通過getBoundingClientRect獲取到dom的x1,y1,x2,y2坐標(biāo)然后進(jìn)行坐標(biāo)比對(duì)即可判斷出來

function overlaps = (a, b) {
   return (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
}

判斷是否是NodeJs環(huán)境

前端的日常開發(fā)是離不開nodeJs的,通過判斷全局環(huán)境來檢測是否是nodeJs環(huán)境

function isNode(){
    return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}

參數(shù)求和

之前看到有通過函數(shù)柯理化形式來求和的,通過reduce一行即可

function sum(...args){
    args.reduce((a, b) => a + b);
}

到此這篇關(guān)于盤點(diǎn)30個(gè)經(jīng)典常用的JavaScript知識(shí)點(diǎn)的文章就介紹到這了,更多相關(guān)JavaScript知識(shí)點(diǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論