[번역 ]12가지 유용한 자바스크립트 Code Snippets

Yul Kang·2023년 5월 15일
0

JS

목록 보기
4/4

원문: https://javascript.plainenglish.io/12-useful-javascript-snippets-for-everyday-problems-4f08ee1ab5e

1. 구조 분해 할당

const data = ["Messi", "35", "Football Player"];
const [name, age, job_title] = data;

console.log(name, age, job_title) // Messi 35 Football Player

2. 배열에서 객체 찾기

const people = [
  {name: "James", job_title: "Accountant"},
  {name: "Dylan", job_title: "Software Engineer"},
  {name: "Terry", job_title: "Lawyer"},
]
let engineer = people.find(data => data.job_title === "Software Engineer")

3. 문자열 뒤집기

const reverse = (input) => {
  return input.split("").reverse().join("");
}
console.log(reverse("Yul Kang")) // gnaK luY
console.log(reverse("Velog")) // goleV

4. 템플릿 문자열

let placeholder1 = "Python";
let placeholder2 = "Rust";

console.log(`I'm a ${placeholder1} developer`);
// I'm a Python developer
console.log(`I'm a ${placeholder2} developer`);
// I'm a Rust developer

5. 한 줄 if 문 (삼항연산자)

// if 문
if (10 > 7) {
  console.log(true);
} else {
  console.log(false);
}

// 삼항연산자
10 > 7 ? console.log(true) : console.log(false);
    

6. 중복 제거하기

function removeDuplicates(array) {
  return [...new Set(array)];
}
const uniqueCity = removeDuplicates(["Seattle", "New York", "Seoul", "Seoul", "LA", "Seattle"]);

console.log(uniqueCity);
// ["Seattle", "New York", "Seoul", "LA"]

7. 문자열을 배열로 나누기

const randomString = "Javascript"
const newArr = [...randomString];

console.log(newArr);
// ['J', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't']

8. 우클릭 감지하기

window.oncontextmenu = () => {console.log("Right Click is Pressed!")}

9. key 또는 value로 dictionary 순회하기

const programming_language = {C++: 1, Java:2, Python: 3};
Object.keys(programming_language).forEach((key) => {
  console.log(key);
});
// C++
// Java
// Python

Object.values(programming_language).forEach((key) => {
  console.log(key);
});
// 1
// 2
// 3

10. Filter Method

// 10. Smart Data Filteration
const jobs = ["Frontend Developer", "Backend Developer", "Data Scientist", "Teacher"]
const filtered_jobs1 = jobs.filter(data => data.length < 10)
const filtered_jobs2 = jobs.filter(data => data.includes("Developer"))

console.log(filtered_jobs1) // [ 'Teacher' ]
console.log(filtered_jobs2) // [ 'Frontend Developer', 'Backend Developer' ]

11. nullish 병합 연산자

const foo = null ?? 'default string';
const baz = 0 ?? 42;

console.log(foo); // default string
console.log(baz); // 0

12. Error Handling

function getRectArea(width, height) {
    if (isNaN(width) || isNaN(height)) {
        throw 'Parameter is not a number!';
    }
}

try {
    getRectArea(3, "A")
} catch (err) {
    console.log(`There was an error: ${err}`)
} finally {
    console.log("This code block is executed regardless of try/catch results")
}
// Output:
// There was an error: Parameter is not a number!
// This code block is executed regardless of try/catch results

0개의 댓글