Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript Snippets

NotificationsYou must be signed in to change notification settings

nhatchimai111/JavaScript-snippets

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 

Repository files navigation

JS snippets logo

JSsnippets on Facebook

find us onFacebook

How to generate a random number in a given range

// Returns a random number(float) between min (inclusive) and max (exclusive)constgetRandomNumber=(min,max)=>Math.random()*(max-min)+min;getRandomNumber(2,10)// Returns a random number(int) between min (inclusive) and max (inclusive)constgetRandomNumberInclusive=(min,max)=>{min=Math.ceil(min);max=Math.floor(max);returnMath.floor(Math.random()*(max-min+1))+min;}getRandomNumberInclusive(2,10);

How to find the difference between two arrays.

constfirstArr=[5,2,1];constsecondArr=[1,2,3,4,5];constdiff=[    ...secondArr.filter(x=>!firstArr.includes(x)),    ...firstArr.filter(x=>!secondArr.includes(x))];console.log('diff',diff)//[3,4]functionarrayDiff(a,b){return[        ...a.filter(x=>b.indexOf(x)===-1),        ...b.filter(x=>a.indexOf(x)===-1)]}console.log('arrayDiff',arrayDiff(firstArr,secondArr))//[3,4]constdifference=(a,b)=>{constsetA=newSet(a);constsetB=newSet(b);return[        ...a.filter(x=>!setB.has(x)),        ...b.filter(x=>!setA.has(x))]};difference(firstArr,secondArr);//[3,4]console.log('difference',difference(firstArr,secondArr))

How to convert truthy/falsy to boolean(true/false)

constmyVar=null;constmySecondVar=1;console.log(Boolean(myVar))// falseconsole.log(!!myVar)// falseconsole.log(Boolean(mySecondVar))// trueconsole.log(!!mySecondVar)// true

How to repeat a string

letaliens='';for(leti=0;i<6;i++){aliens+='👽'}//👽👽👽👽👽👽Array(6).join('👽')//👽👽👽👽👽👽'👽'.repeat(6)//👽👽👽👽👽👽

Check how long an operation takes

//The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds.//performance.now() is relative to page load and more precise in orders of magnitude.//Use cases include benchmarking and other cases where a high-resolution time is required//such as media (gaming, audio, video, //etc.)varstartTime=performance.now();doSomething();constendTime=performance.now();console.log("this doSomething took "+(endTime-startTime)+" milliseconds.");

Two ways to remove an item in a specific in an array

//Mutating wayconstmuatatedArray=['a','b','c','d','e'];muatatedArray.splice(2,1)console.log(muatatedArray)//['a','b','d','e']//Non-mutating wayconstnonMuatatedArray=['a','b','c','d','e'];constnewArray=nonMuatatedArray.filter((item'index)=>!(index===2));console.log(newArray)//['a','b','d','e']

Did you know you can flat an array?

constmyArray=[2,3,[4,5],[7,7,[8,9,[1,1]]]];myArray.flat()// [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]myArray.flat(1)// [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]myArray.flat(2)// [2, 3, 4, 5 ,7,7, 8, 9, [1, 1]]//if you dont know the depth of the array you can use infinitymyArray.flat(infinity)// [2, 3, 4, 5 ,7,7, 8, 9, 1, 1];

Get unique values in an array

constnumbers=[1,1,3,2,5,3,4,7,7,7,8];//Ex1constunieqNumbers=numbers.filter((v,i,a)=>a.indexOf(v)===i)console.log(unieqNumbers)//[1,3,2,5,4,7,8]//Ex2constunieqNumbers2=Array.from(newSet(numbers))console.log(unieqNumbers2)//[1,3,2,5,4,7,8]//Ex3constunieqNumbers3=[...newSet(numbers)]console.log(unieqNumbers3)//[1,3,2,5,4,7,8]//EX4 lodashconstunieqNumbers4=_.uniq(numbers)console.log(unieqNumbers4)//[1,3,2,5,4,7,8]

Copy Text to Clipboard

functioncopyToClipboard(){constcopyText=document.getElementById("myInput");copyText.select();document.execCommand("copy");}//new APIfunctioncopyToClipboard(){navigator.clipboard.writeText(document.querySelector('#myInput').value)}

Nested Destructuring

constuser={id:459,name:'JS snippets',age:29,education:{degree:'Masters'}}const{education :{ degree}}=user;console.log(degree)//Masters

URLSearchParams

//The URLSearchParams interface defines utility methods to work with the query string of a URL.consturlParams=newURLSearchParams("?post=1234&action=edit");console.log(urlParams.has('post'));// trueconsole.log(urlParams.get('action'));// "edit"console.log(urlParams.getAll('action'));// ["edit"]console.log(urlParams.toString());// "?post=1234&action=edit"console.log(urlParams.append('active','1'));// "?post=1234&action=edit&active=1"

Shuffle an array

constlist=[1,2,3,4,5,6,7,8,9];constshuffle=list.sort(func);functionfunc(a,b){return0.5-Math.random();}console.log(shuffle);

Count elements in an array

constmyFruits=['Apple','Orange','Mango','Banana','Apple','Apple','Mango']//first optionconstcountMyFruits=myFruits.reduce((countFruits,fruit)=>{countFruits[fruit]=(countFruits[fruit]||0)+1;returncountFruits},{})console.log(countMyFruits)// { Apple:3, Banana:1, Mango:2, Orange:1 }//seconf optionconstfruitsCounter={};for(constfruitofmyFruits){fruitsCounter[fruit]=fruitsCounter[fruit] ?fruitsCounter[fruit]+1 :1;}console.log(fruitsCounter)// { Apple:3, Banana:1, Mango:2, Orange:1 }

Aliases with JavaScript Destructuring

//There are cases where you want the destructured variable to have a different name than the property nameconstobj={name:"JSsnippets"};// Grabs obj.name as { pageName }const{name:pageName}=obj;//log our aliasconsole.log(pageName)// JSsnippets

The Object.is() method determines whether two values are the same value

Object.is('foo','foo');// trueObject.is(null,null);// trueObject.is(Nan,Nan);// true 😱constfoo={a:1};constbar={a:1};Object.is(foo,foo);// trueObject.is(foo,bar);// false

About

JavaScript Snippets

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp