1. 배열 선언 및 초기화
또는 같은 기본값을 사용하여 특정 크기의 배열을 초기화할 수 있습니다 "". 1-D 배열에 이것을 사용했을 수도 있지만 2-D 배열/행렬을 초기화하는 것은 어떻습니까?null0
const array = Array(5).fill('');
// Output
(5) ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(()=>Array(5).fill(0));
// Output
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
2. 합계, 최소값, 최대값 알아보기
reduce기본적인 수학 연산을 빠르게 찾기 위해서는 방법을 활용해야 합니다 .
const array = [5,4,7,8,9,2];
- 합집합
array.reduce((a,b) => a+b);
// Output: 35
- 맥스
array.reduce((a,b) => a>b?a:b);
// Output: 9
- 최소
array.reduce((a,b) => a<b?a:b);
// Output: 2
3. 문자열, 숫자 또는 객체의 배열 정렬
문자열 정렬을 위한 내장 메소드가 있지만 sort()숫자 reverse()나 객체 배열은 어떻습니까?
숫자와 개체를 증가 및 감소 순서로 정렬하는 방법도 확인해 보겠습니다.
- 문자열 배열 정렬
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]
- 숫자 배열 정렬
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// Output
(6) [100, 40, 25, 10, 5, 1]
- 객체 배열 정렬
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// Output
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
4. 배열에서 잘못된 값을 필터링해야 했던 적이 있습니까?
0, undefined, null, false, "", 와 같은 거짓 값은 ''아래 트릭을 통해 쉽게 생략할 수 있습니다.
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// Output
(3) [3, 6, 7]
5. 다양한 조건에 논리 연산자를 사용하세요
중첩된 if..else 또는 대소문자 전환을 줄이려면 기본 논리 연산자를 사용하면 됩니다 AND/OR.
function doSomething(arg1){
arg1 = arg1 || 10;
// set arg1 to 10 as a default if it’s not already set
return arg1;
}
let foo = 10;
foo === 10 && doSomething();
// is the same thing as if (foo == 10) then doSomething();
// Output: 10
foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// Output: 10
6. 중복 값 제거
중복 항목을 찾아 제거하기 위해 배열에서 부울 true/false를 반환하는 indexOf()첫 번째 발견 인덱스 또는 최신 인덱스를 반환하는 for 루프를 사용했을 수 있습니다 . includes()여기에 2가지 더 빠른 접근 방식이 있습니다.
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
7. 카운터 개체 또는 맵 만들기
대부분의 경우, 빈도/발생을 값으로 사용하여 변수를 키로 추적하는 카운터 개체나 맵을 생성하여 문제를 해결해야 합니다.
let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// Output
{k: 2, a: 3, p: 2, i: 2, l: 2}
그리고
const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// Output
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
8. 삼항 연산자는 멋지다
삼항 연산자를 사용하면 중첩된 조건문 if..elseif..elseif를 피할 수 있습니다.
function Fever(temp) {
return temp > 97 ? 'Visit Doctor!'
: temp < 97 ? 'Go Out and Play!!'
: temp === 97 ? 'Take Some Rest!';
}
// Output
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"
9. 기존의 Once에 비해 더 빠른 for 루프
- for기본적으로 인덱스를 가져 오지만 for..inarr[index]를 사용할 수 있습니다.
- for..in숫자가 아닌 것도 허용하므로 피하십시오.
- forEach, for...of요소를 직접 가져옵니다.
- forEach색인도 얻을 수 있지만 얻을 수 for...of는 없습니다.
- for배열의 구멍을 고려 하지만 for...of다른 2개는 그렇지 않습니다.
10. 2개 개체 병합
일상적인 작업에서 여러 개체를 병합해야 하는 경우가 많습니다.
const user = {
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};
// Output
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
11. 화살표 기능
화살표 함수 표현식은 기존 함수 표현식에 대한 간단한 대안이지만 제한적이며 모든 상황에서 사용할 수는 없습니다. 어휘 범위(상위 범위)가 있고 자체 범위가 없으므로 this정의 arguments된 환경을 참조합니다.
const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// Output
"Kapil"
하지만
const person = {
name: 'Kapil',
sayName : () => {
return this.name;
}
}
person.sayName();
// Output
""
12. 선택적 연결
선택적 체인 ?. ? 이전의 값이 있으면 평가를 중지합니다. 정의되지 않았거나 null이며 정의되지 않음을 반환합니다.
const user = {
employee: {
name: "Kapil"
}
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// Output: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined
13. 배열 섞기
내장된 방법을 사용합니다 Math.random().
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
return Math.random() - 0.5;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
14. Nullish 병합 연산자
null 병합 연산자(??)는 왼쪽 피연산자가 null이거나 정의되지 않은 경우 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자입니다.
const foo = null ?? 'my school';
// Output: "my school"
const baz = 0 ?? 42;
// Output: 0
15. 나머지 및 스프레드 연산자
그 신비한 점 3개는 ...쉬거나 퍼질 수도 있어요!🤓
function myFun(a, b, ...manyMoreArgs) {
return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");
// Output: 6
그리고
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
lyrics;
// Output:
(5) ["head", "shoulders", "knees", "and", "toes"]
16. 기본 매개변수
const search = (arr, low=0,high=arr.length-1) => {
return high;
}
search([1,2,3,4,5]);
// Output: 4
17. 10진수를 2진수 또는 16진수로 변환
우리는 문제를 해결하면서 많은 도움 기능을 달성하기 위해 .toPrecision()또는 같은 내장된 방법을 사용할 수 있습니다 ..toFixed()
const num = 10;
num.toString(2);
// Output: "1010"
num.toString(16);
// Output: "a"
num.toString(8);
// Output: "12"
18. Destructuring을 사용한 Simple Swap 2 값
let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]
// Output
(2) [8, 5]
19. 단일 라이너 회문 검사
글쎄, 이것은 전체적으로 속기적인 트릭은 아니지만 문자열을 가지고 연주하는 데 대한 명확한 아이디어를 제공할 것입니다.
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// Output: true
20. 객체 속성을 속성 배열로 변환
Object.entries(), 및 Object.keys()_Object.values()
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]