반응형

nullish 병합 연산자

nullish 병합 연산자(nullish coalescing operator)

 

https://ko.javascript.info/nullish-coalescing-operator#ref-778

 

nullish 병합 연산자 '??'

 

ko.javascript.info

 

nullish 병합 연산자(nullish coalescing operator) ??를 사용하면 짧은 문법으로 여러 피연산자 중 그 값이 ‘확정되어있는’ 변수를 찾을 수 있습니다.

a ?? b의 평가 결과는 다음과 같습니다.

  • a가 null도 아니고 undefined도 아니면 a
  • 그 외의 경우는 b

nullish 병합 연산자 ??없이 x = a ?? b와 동일한 동작을 하는 코드를 작성하면 다음과 같습니다.

x = (a !== null && a !== undefined) ? a : b;

비교 연산자와 논리 연산자만으로 nullish 병합 연산자와 같은 기능을 하는 코드를 작성하니 코드 길이가 길어지네요.

또 다른 예시를 살펴봅시다. firstName, lastName, nickName이란 변수에 사용자 이름이나 별명을 저장하는데, 사용자가 아무런 정보도 입력하지 않는 케이스도 허용한다고 해보겠습니다.

화면엔 세 변수 중 실제 값이 있는 변수의 값을 출력하는데, 세 변수 모두 값이 없다면 '익명의 사용자’가 출력되도록 해보죠.

이럴 때 nullish 병합 연산자 ??를 사용하면 값이 정해진 변수를 간편하게 찾아낼 수 있습니다.

 
 
let firstName = null;
let lastName = null;
let nickName = "바이올렛";

// null이나 undefined가 아닌 첫 번째 피연산자
alert(firstName ?? lastName ?? nickName ?? "익명의 사용자"); // 바이올렛

'??'와 '||'의 차이

nullish 병합 연산자는 OR 연산자 ||와 상당히 유사해 보입니다. 실제로 위 예시에서 ??를 ||로 바꿔도 그 결과는 동일하기까지 하죠. 관련 내용은 이전 챕터에서 살펴본 바 있습니다.

그런데 두 연산자 사이에는 중요한 차이점이 있습니다.

  • ||는 첫 번째 truthy 값을 반환합니다.
  • ??는 첫 번째 정의된(defined) 값을 반환합니다.

null과 undefined, 숫자 0을 구분 지어 다뤄야 할 때 이 차이점은 매우 중요한 역할을 합니다.

예시를 살펴봅시다.

height = height ?? 100;

height에 값이 정의되지 않은경우 height엔 100이 할당됩니다.

이제 ??와 ||을 비교해봅시다.

 
 
let height = 0;

alert(height || 100); // 100
alert(height ?? 100); // 0

height || 100은 height에 0을 할당했지만 0을 falsy 한 값으로 취급했기 때문에 null이나 undefined를 할당한 것과 동일하게 처리합니다. 따라서 height || 100의 평가 결과는 100입니다.

반면 height ?? 100의 평가 결과는 height가 정확하게 null이나 undefined일 경우에만 100이 됩니다. 예시에선 height에 0이라는 값을 할당했기 때문에 얼럿창엔 0이 출력됩니다.

이런 특징 때문에 높이처럼 0이 할당될 수 있는 변수를 사용해 기능을 개발할 땐 ||보다 ??가 적합합니다.

연산자 우선순위

??의 연산자 우선순위 5로 꽤 낮습니다.

따라서 ??는 =와 ? 보다는 먼저, 대부분의 연산자보다는 나중에 평가됩니다.

그렇기 때문에 복잡한 표현식 안에서 ??를 사용해 값을 하나 선택할 땐 괄호를 추가하는 게 좋습니다.

 
 
let height = null;
let width = null;

// 괄호를 추가!
let area = (height ?? 100) * (width ?? 50);

alert(area); // 5000

그렇지 않으면 *가 ??보다 우선순위가 높기 때문에 *가 먼저 실행됩니다.

결국엔 아래 예시처럼 동작하겠죠.

// 원치 않는 결과
let area = height ?? (100 * width) ?? 50;

??엔 자바스크립트 언어에서 규정한 또 다른 제약사항이 있습니다.

안정성 관련 이슈 때문에 ??는 &&나 ||와 함께 사용하지 못합니다.

아래 예시를 실행하면 문법 에러가 발생합니다.

 
 
let x = 1 && 2 ?? 3; // SyntaxError: Unexpected token '??'

이 제약에 대해선 아직 논쟁이 많긴 하지만 사람들이 ||를 ??로 바꾸기 시작하면서 만드는 실수를 방지하고자 명세서에 제약이 추가된 상황입니다.

제약을 피하려면 괄호를 사용해주세요.

 
 
let x = (1 && 2) ?? 3; // 제대로 동작합니다.

alert(x); // 2

요약

  • nullish 병합 연산자 ??를 사용하면 피연산자 중 ‘값이 할당된’ 변수를 빠르게 찾을 수 있습니다.
    // height가 null이나 undefined인 경우, 100을 할당
    height = height ?? 100;
  • ??는 변수에 기본값을 할당하는 용도로 사용할 수 있습니다.
  • ??의 연산자 우선순위는 대다수의 연산자보다 낮고 ?와 = 보다는 높습니다.
  • 괄호 없이 ??를 ||나 &&와 함께 사용하는 것은 금지되어있습니다.
반응형
반응형

 

https://swiperjs.com/demos

 

Swiper Demos

Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

swiperjs.com

 

반응형
반응형
[JavaScript] 브라우저에서 뒤로가기 했을때, 자바스크립트 실행하기
 

// javascript
window.onpageshow = function(event){
	if( event.persisted ){
        console.log("BFCache로부터 복원됨");
	}else{
        console.log("새로 열린 페이지");
	}
}

// jquery 
$(window).bind("pageshow", function(event){	
	if( event.originalEvent.persisted ){
        console.log("BFCache로부터 복원됨");
	}else{
        console.log("새로 열린 페이지");
	}
});
반응형
반응형

History API (https://developer.mozilla.org/ko/docs/Web/API/History_API)

DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. history는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는, 유용한 메서드와 속성을 가집니다.

 

History.pushState  페이지 이동 없이 주소만 바꿔준다. (브라우저의 뒤로가가 버튼이 활성화 된다.)

브라우저 페이지를 이동하게 되면 window.onpopstate 라는 이벤트가 발생하게 되는데, pushState  했을때는 popstate 이벤트가 발생하지않고,  / 앞으로 가기를 클릭 했을때 popstate 이벤트가 발생하게 된다.

즉, pushState 와 popstate 둘을 이용하여 SPA 의 페이지 전환을 구현할 수 있다.

 

기본 형태 - history.pushState(state, title, url);

State : 브라우저 이동  넘겨줄 데이터 (popstate 에서 받아서 원하는 처리를 해줄  있음)

Title : 변경할 브라우저 제목 (변경 원치 않으면 null)

Url : 변경할 주소

 

사용예)

window.onpopstate = function(e) { 
    console.log(`${JSON.stringify(e.state)} | ${location.origin} | ${location.pathname}`);
}

var state = {page_id : 1, data : 'test'};
var url = location.origin + '/myPage';
history.pushState(state, null, url);

 코드를 실행하면 history.pushState  수행했을때 브라우저 주소에 /myPage  붙는걸   있고,

뒤로가기를(원래 url) 한뒤 다시 앞으로(pushState 추가된 url) 가기를 클릭 하면

콘솔 출력값으로 {"page_id":1,"data":"test"} | http://localhost:5000 | /myPage  출력된다.

 

 

* https://kwangsunny.tistory.com/28

반응형
반응형

[javascript] 새로고침 없이 파라미터 제거/수정

 

Remove URL parameters without refreshing page

window.history.pushState({}, document.title, "/" + myNewURL );

https://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page

 

Remove URL parameters without refreshing page

I am trying to remove everything after the "?" in the browser url on document ready. Here is what I am trying: jQuery(document).ready(function($) { var url = window.location.href; url = url...

stackoverflow.com

 

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState()

 

For one liner fans, try this out in your console/firebug and this page URL will change:

window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

 

History: pushState() method
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

 

History: pushState() method - Web APIs | MDN

In an HTML document, the history.pushState() method adds an entry to the browser's session history stack.

developer.mozilla.org

 

History.replaceState() https://developer.mozilla.org/ko/docs/Web/API/History/replaceState

 

History.replaceState() - Web API | MDN

History.replaceState() 메서드는 현재 history를 수정해 메소드의 매개 변수에 전달 된 stateObj, title, URL로 대체합니다. 이 방법은 특히 일부 유저의 동작에 대한 응답으로 history 객체의 상태나 현재 history

developer.mozilla.org

 

반응형
반응형

[javascript] 파라미터 제거하기. remove url parameters with javascript or jquery

 

https://stackoverflow.com/questions/4651990/remove-url-parameters-with-javascript-or-jquery

 

remove url parameters with javascript or jquery

I am trying to use the youtube data api to generate a video playlist. However, the video urls require a format of: youtube.com/watch?v=3sZOD3xKL0Y but what the api generates is: youtube.com/wa...

stackoverflow.com

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.slice( 0, url.indexOf('&') );

alert( url );

 

var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';

console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org



window.location.replace(window.location.pathname)

https://jsfiddle.net/mill01/hxrejz5L/6/

 

반응형
반응형

A list of one-liners you should know to up your knowledge of JavaScript.

1.# Copy content to the clipboard

In order to improve the user experience of the website, we often need to copy the content to the clipboard, so that users can paste it to the designated place.

const copyToClipboard = (content) => navigator.clipboard.writeText(content)

copyToClipboard("Hello fatfish")

2.# Get the mouse selection

Have you encountered this kind of situation before?

We need to get the content selected by the user.

const getSelectedText = () => window.getSelection().toString()

getSelectedText()

3.# Shuffle an array

Shuffle an array? This is very common in lottery programs, but it’s not truly random.

const shuffleArray = array => array.sort(() => Math.random() - 0.5)

shuffleArray([ 1, 2,3,4, -1, 0 ]) // [3, 1, 0, 2, 4, -1]

4.# Convert rgba to hexadecimal

We can convert the rgba and hexadecimal color values to each other.

const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')

rgbaToHex(0, 0 ,0) // #000000
rgbaToHex(255, 0, 127) //#ff007f

5.# Convert hexadecimal to rgba

const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
  return `rgba(${r}, ${g}, ${b}, 1)`;
}

hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.# Get the average of multiple numbers

Using reduce we can get the average value of a set of arrays very conveniently.

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length

average(0, 1, 2, -1, 9, 10) // 3.5

7.# Check if a number is even or odd

How can you tell if a number is odd or even?

const isEven = num => num % 2 === 0

isEven(2) // true
isEven(1) // false

8.# Deduplicate elements in an array

To remove duplicate elements in an array, using Set will make it very easy.

const uniqueArray = (arr) => [...new Set(arr)]

uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ]) // [1, 2, 3, 4, 5, -1, 0]

9.# Check if an object is an empty object

Is it easy to determine if an object is empty?

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

isEmpty({}) // true
isEmpty({ name: 'fatfish' }) // false

10.# Reverse a string

const reverseStr = str => str.split('').reverse().join('')

reverseStr('fatfish') // hsiftaf

11.# Calculate the interval between two dates

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)

dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519

12.# Find the day of the year in which the date falls

Today is June 23, 2023, so what day is it this year?

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

dayInYear(new Date('2023/06/23'))// 174

13.# Capitalize the first letter of the string

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello fatfish")  // Hello fatfish

14.# Generate a random string of specified length

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')

generateRandomString(12) // cysw0gfljoyx
generateRandomString(12) // uoqaugnm8r4s

15.# Get a random integer between two integers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

random(1, 100) // 27
random(1, 100) // 84
random(1, 100) // 55

16.# Specified digits rounded

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(3.1415926, 3) //3.142
round(3.1415926, 1) //3.1

17.# Clear all cookies

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))

18.# Detect if it is dark mode

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

19.# Scroll to the top of the page

const goToTop = () => window.scrollTo(0, 0)

goToTop()

20.# Determine if it is an Apple device

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform)

isAppleDevice()

21.# Random Boolean values

const randomBoolean = () => Math.random() >= 0.5

randomBoolean()

22.# Get the type of the variable

const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

typeOf('')     // string
typeOf(0)      // number
typeOf()       // undefined
typeOf(null)   // null
typeOf({})     // object
typeOf([])     // array
typeOf(0)      // number
typeOf(() => {})  // function

23.# Determine if the current tab is active or not

const checkTabInView = () => !document.hidden

24.# Check if an element is focused

const isFocus = (ele) => ele === document.activeElement

25.# Random IP

const generateRandomIP = () => {
  return Array.from({length: 4}, () => Math.floor(Math.random() * 256)).join('.');
}

generateRandomIP() // 220.187.184.113
generateRandomIP() // 254.24.179.151

More content at PlainEnglish.io.

 

 

https://javascript.plainenglish.io/25-killer-javascript-one-liners-thatll-make-you-look-like-a-pro-d43f08529404

 

25 Killer JavaScript One-Liners That’ll Make You Look Like a Pro

A list of one-liners you should know to up your knowledge of JavaScript.

javascript.plainenglish.io

 

반응형
반응형

숫자에 콤마 제거

 

replace comma

금액필드에 , 제거 해야할 경우

 

amount.replace(",", "");

-> only replace one comma

-> 앞에 한개만 제거

 

amount.replace(/,/g, '');

-> replace all comma

-> 모든 콤마 제거

-> 정규식

 

How to replace all of comma

 

Result)

amount = "1,000,000"

 

amount.replace(",", "");

1000,000

 

amount.replace(/,/g, '');

1000000

반응형

+ Recent posts