멋진 자바스크립트 속기 10개.

안녕하세요.👋
오늘 여러분과 좋은 자바스크립트 속기 10개를 공유하고 싶습니다. 이 속기는 당신이 더 적은 코드를 작성하고 더 많은 일을 하며 속도를 높일 수 있도록 도와줍니다.
우리 시작합시다!

1. 배열 병합

직접:
우리는 보통 수조 concat() 방법을 사용하여 두 수조를 합친다.concat() 방법은 두 개 이상의 그룹을 통합하는 데 쓰인다.이 방법은 기존 그룹을 변경하지 않고 새 그룹을 되돌려줍니다.다음은 간단한 예입니다.
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);

console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]

속기:
다음과 같이 ES6 확장 연산자(...)를 사용하여 이 연산자를 조금 줄일 수 있습니다.
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];  // <-- here

console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
우리의 생산량은 여전히 이전과 같다.😃

2. 배열 병합(하지만 시작할 때)

직접:
가령 우리가 apples수 그룹의 모든 항목을 fruits수 그룹의 시작에 추가하기를 원한다면, 이전 예시에서 보듯이 끝에 추가하는 것이 아니라. Array.prototype.unshift() 을 사용하면 다음과 같은 이점을 얻을 수 있습니다.
let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];

// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)

console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
현재 이 두 개의 붉은 사과와 녹색 사과는 합병 후 끝 위치가 아니라 시작 위치에 있다.

속기:
다음과 같이 ES6 확장 연산자(...)를 사용하여 이 긴 코드를 다시 줄일 수 있습니다.
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒'];  // <-- here

console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]

3. 클론 어레이

직접:
다음과 같이 Array slice() 방법을 사용하여 스토리지를 손쉽게 복제할 수 있습니다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

속기:
ES6 Spread Operator(...)를 사용하면 다음과 같은 어레이를 복제할 수 있습니다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits];  // <-- here

console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

4. 분해 작업

직접:
배열을 사용할 때 다음과 같이 배열 "패키지해제"를 하나의 변수로 만들어야 하는 경우가 있습니다.
let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];

console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

속기:
다음과 같이 Destructuring assignment을 사용하여 한 라인에서 동일한 결과를 얻을 수 있습니다.
let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples;  // <-- here

console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

5. 템플릿 텍스트

직접:
일반적으로 우리는 문자열에 표현식을 추가해야 할 때 다음과 같이 합니다.
// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!

// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10

속기:
Template literals에 대해 우리는 백틱스(`)를 사용할 수 있다. 이것은 우리가 모든 표현식을 문자열에 삽입할 수 있도록 한다. 방법은 그것을 ${...}에 포장하는 것이다. 아래와 같다.
// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`);  // <-- No need to use + var + anymore
//=> Hello, Palash!

// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. 순환

직접:for 순환을 사용하면 우리는 다음과 같은 그룹을 순환할 수 있다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] );  // <-- get the fruit at current index
}

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

속기:
for...of 문을 사용하여 동일한 결과를 얻을 수 있지만 아주 적은 코드만 필요합니다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using for...of statement 
for (let fruit of fruits) {
  console.log( fruit );
}

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

7. 화살표 기능

직접:
수조에서 순환하기 위해서, 우리도 수조 forEach() 방법을 사용할 수 있다.그러나 우리는 더 많은 코드를 작성해야 한다. 이것은 우리가 위에서 본 가장 흔히 볼 수 있는 for 순환보다 적지만 여전히 for...of 문장보다 많다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

속기:
그러나 Arrow function expressions을 사용하면 다음과 같이 전체 루프 코드를 한 줄에 작성할 수 있습니다.
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit ));  // <-- Magic ✨

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
저는 주로 화살표 함수를 가진 forEach 순환을 사용하지만 순환의 약자 형식인 for...of 문장과 forEach 순환을 보여 드리고 싶습니다.이렇게 하면 너는 자신의 취향에 따라 네가 좋아하는 모든 코드를 사용할 수 있다.😃

8. 배열에서 객체 찾기

직접:
객체 배열에서 객체를 찾으려면 일반적으로 for 루프를 사용합니다.
let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  for (let index = 0; index < arr.length; index++) {

    // Check the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> 🍎

      // A match was found, return this object
      return arr[index];
    }
  }
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

속기:
정말!이 논리를 실현하기 위해서 우리는 반드시 많은 것을 써야 한다.그러나 수조 find() 방법과 화살표 함수 =>을 사용하면 우리는 한 줄에서 이 점을 쉽게 실현할 수 있다. 다음과 같다.
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

9. 문자열을 정수로 변환

직접:
parseInt() 함수는 문자열을 분석하고 정수를 반환하는 데 사용됩니다.
let num = parseInt("10")

console.log( num )         //=> 10
console.log( typeof num )  //=> "number"

속기:
다음과 같이 문자열 앞에 + 접두어를 추가하여 동일한 결과를 얻을 수 있습니다.
let num = +"10";

console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true

10. 단락 평가

직접:
이러한 오류 값 대신 다른 값을 기반으로 값을 설정해야 하는 경우 일반적으로 if-else 문을 사용합니다.
function getUserRole(role) {
  let userRole;

  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {

    // else set the `userRole` as USER
    userRole = 'USER';
  }

  return userRole;
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

속기:
그러나 단락 평가(||)를 사용하면 우리는 한 줄에서 이렇게 할 수 있다.
function getUserRole(role) {
  return role || 'USER';  // <-- here
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"
기본적으로 expression1 || expression2은 실제 표현식에 따라 계산된 단락이다.그래서 첫 번째 부분이 사실이라면 표현식의 나머지 부분을 계산하는 데 신경 쓰지 말라는 말과 같다.
마지막으로 저는 Jeff Atwood의 한 마디를 공유함으로써 본문을 끝내고 싶습니다.

Code is only our enemy because there are so many of us programmers writing so damn much of it. If you can’t get away with no code, the next best thing is to start with brevity.

If you love writing code — really, truly love to write code — you’ll love it enough to write as little of it as possible.


만약 네가 이 문장을 좋아한다면, 반드시❤ 네.
너도 나의 이전 블로그를 볼 수 있다.



즐거운 코딩!

지역사회 투입

  • 화살표 기능this 컨텍스트가 필요하지 않은 경우 화살표 함수를 사용하여 다음을 더 줄일 수 있습니다.
    let fruits = ['🍉', '🍊', '🍇', '🍎'];
    fruits.forEach(console.log);
    

  • 배열에서 객체 찾기
    객체 분해 및 화살표 함수를 사용하여 보다 단순화할 수 있습니다.
    // Get the object with the name `Apples` inside the array
    const getApples = array => array.find(({ name }) => name === "Apples");
    
    let result = getApples(inventory);
    console.log(result);
    //=> { name: "Apples", quantity: 10 }
    
    단락 평가 대안
    const getUserRole1 = (role = "USER") => role;
    const getUserRole2 = role => role ?? "USER";
    const getUserRole3 = role => role ? role : "USER";
    
    피드백 감사합니다!❤️

    좋은 웹페이지 즐겨찾기