반응형
링크드인에서 어떤 외국인 개발자가 올린 자바스크립트 코드스니펫 20가지를 가져와봤다.
자주쓴다니까 마냥 가져다 쓰기에는 고려해야할 사항이 몇가지 있는것 같아서
자바스크립트 공부도 할겸 짧은 코멘트와 함께 포스팅 해보려 한다.
1. 현재 시간값 구하기
const now = new Date();
2. 배열인지 체크하기
Array.isArray(data); // true , false
3. 배열 합치기
const arr1 = [1,2];
const arr2 = [3,4];
const newArray = arr1.concat(arr2); // [1,2,3,4]
4. 배열에서 중복값 제거하기
const array = [1,1,2,3,3,3,4];
const uniqueArray = [...new Set(array)]; // [1, 2, 3, 4]
여기서 Spread(...)용법 사용해주는 이유는 중복값을 제거한 Set 객체를 배열로서 사용하기위해 배열로 확장해주어야 하기 때문이다.
Spread용법이 iterable한 객체(array, set, map, 문자열)와 조합되었을때 배열로 확장해주는 역할을 한다.
5. 오름차순으로 배열 정렬하기
const array = [3,4,1,2];
const newArray = array.sort((a,b) => a-b);
console.log(array); // [1, 2, 3, 4]
console.log(newArray); // [1, 2, 3, 4]
주의해야할 점이 sort 메서드를 사용하면 원본 배열도 정렬되면서 값이 변한다.
원본값을 유지하면서 정렬만 하고싶은 경우에는 다른 방식으로 정렬을 해야 한다.
1. lodash 라이브러리 sortBy 사용하기
const _ = require('lodash');
const array = [3, 1, 2];
const sortedArray = _.sortBy(array);
console.log(sortedArray); // [1, 2, 3]
console.log(array); // [3, 1, 2] (원본 배열은 변경되지 않음)
2. 원본배열 복사해서 정렬하기
const array = [3, 1, 2];
const sortedArray = [...array].sort((a,b) => a-b);
console.log(sortedArray); // [1, 2, 3];
console.log(array); // [3, 1, 2]; (원본 배열은 변경되지 않음)
6. 배열 순서 뒤집기
const array = [4, 2, 3, 1];
array.reverse();
console.log(array); // [1, 3, 2, 4];
정렬과 마찬가지로 reverse 메서드 역시 원본값을 변형시킨다.
7. 문자열 숫자로 변경하기
const string = "13";
const number = parseInt(string);
console.log(typeof number); // "number"
문자열이 위에 코드스니펫처럼 숫자로 시작한다면 간단하게 "+" 연산자만 이용해서 숫자로 변환시킬 수도 있다.
const string = "44";
const number = +string;
console.log(typeof number); // "number"
8. 두가지 숫자값 사이의 랜덤한 숫자 생성하기
const max = 10;
const min = 8;
const randomNumber = Math.floor(Math.random() * (max - min +1)) + min;
console.log(randomNumber) // 8 or 9 or 10
9. 문자열에 찾고싶은 문자값이 존재하는지 확인하기
const string = "apple";
const sub = "e";
console.log(string.includes(sub)); // true or false
10. 객체의 길이
const obj = {1:'a', 2:'b', 3:'c'};
console.log(Object.keys(obj).length); // 3
11. 객체 -> 배열 전환
const obj = {1:'a', 2:'b', 3:'c'};
const array = Object.entries(obj);
console.log(array); // [["1", "a"], ["2", "b"], ["3", "c"]]
12. 빈객체 여부체크
const obj = {};
const array = Object.entries(obj);
console.log(array); // []
13. 현재 URL 값 가져오기
const currentUrl = window.location.href;
14. 특정 Url로 리다이렉트 시키기
const url = "www.naver.com";
window.location.replace(url);
위의 방법은 라이브러리없이 자바스크립트만 사용하는 환경에서 쓰이는것이 적합하고
React 같은 라이브러리 or 프레임워크를 우회하여 라우팅을 시키기때문에 적합하지 않다.
15. 쿠키 세팅
document.cookie = "name=value; expires=date; path=path; domain=domain; secure";
16. 쿠키 값 가져오기
const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$|^.*$/, "$1");
17. 쿠키 존재유무 체크
document.cookie.split(';').some((item) => item.trim().startWith('name='));
18. 쿠키 제거
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=path; domain=domain; secure";
19. 현재 뷰포트 치수 가져오기
const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
20. 클립보드에 텍스트 복사하기
navigator.clipboard.writeText(text);
댓글에 잘못된 내용 피드백 주시면 수정 하겠습니다.
좋은 피드백 항상 환영입니다.
반응형
'JavaScript' 카테고리의 다른 글
Javascript - Scope(유효범위) (0) | 2021.08.03 |
---|---|
변수 호이스팅(Hoisting) (0) | 2021.06.23 |
버튼 클릭시 눌린 버튼 상태 변화(Javascript) (1) | 2021.05.02 |
눈누 무료폰트 프로젝트에 적용하기 (1) | 2021.04.26 |