덜 알려진 JavaScript 트릭
생성자 브래킷은 선택 사항입니다.
const newDate = new Date(); // valid
const myClass = new MyClass(); // valid
const anotherDate = new Date; // Also valid
const myClass = new MyClass; // You bet this is valid
이러한 대괄호가 필요한 유일한 경우는 생성자가 인수를 예상하는 경우입니다.
성명으로
🚨
with
문은 권장하지 않으며 ES5 엄격 모드에서는 금지되어 있습니다.with
문은 문의 범위 체인을 확장합니다. with
는 범위 체인에 전달된 object
의 모든 속성을 추가합니다.const person = {
name: "Parwinder",
age: 33,
work: "Software Architect"
}
with (person) {
console.log(`Hi, I am ${name}, and I am ${ age } years old. I work as a ${work}.`);
// Hi, I am Parwinder, and I am 33 years old. I work as a Software Architect.
}
함수 인수
모든 함수(화살표 함수 제외)에는 함수에 전달된 모든 인수의 값을 포함하는
arguments
배열과 유사한 객체가 있습니다.function foo(a, b, c) {
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
console.log(arguments[2]); // 3
}
foo(1, 2, 3);
arguments
에는 두 가지 속성이 있습니다.arguments.callee
: 호출되는 함수arguments.callee.caller
: 현재 함수를 호출한 함수🚨위의
with
구문과 마찬가지로 ES5 strict 모드에서는 callee
와 caller
가 금지되어 있습니다.순수 개체
순수 객체는 프로토타입에 기능이 없습니다.
const x = {};
이렇게 하면 객체가 생성되지만 프로토타입에는
constructor
및 hasOwnProperty
, isPrototypeOf
및 toString
와 같은 메서드가 있습니다.const x = Object.create(null);
create(null)
프로토타입이 없는 객체를 생성합니다! 🤯어레이에서 중복 제거
const arr = [1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 6, 6, 6, 7, 8, 9];
const arrWithoutDuplicates = [...new Set(arr)];
console.log(arrWithoutDuplicates); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
집합의 핵심 속성은 고유한 값을 갖는 것입니다. 배열에서 Set을 가져오면 Spread(...) 연산자를 사용하여 빈 배열로 확산할 수 있습니다.
선택적 연결
하위 개체의 존재 여부를 모르는 중첩된 개체 속성에 액세스할 때마다 다음과 같이 끝납니다.
const nestedObject = {
name: "Parwinder",
details: {
age: 33,
cars: {
first: "jeep",
second: "tesla",
accessories: {
x: 200,
y: 300
}
}
}
}
if (nestedObject &&
nestedObject.details &&
nestedObject.details.cars &&
nestedObject.details.cars.accessories) {
console.log(nestedObject.details.cars.accessories.x); // 200
}
선택적인 체인은 어수선함을 제거합니다. 선택적 연결을 사용하여 다음을 수행할 수 있습니다.
const nestedObject = {
name: "Parwinder",
details: {
age: 33,
cars: {
first: "jeep",
second: "tesla",
accessories: {
x: 200,
y: 300
}
}
}
}
console.log(nestedObject?.details?.cars?.accessories?.x); // 200
🚨 Optional Chaining이 ES2020/ES11 사양에 적용되었습니다! 여기에서 확인하십시오: https://tc39.es/ecma262/2020/
Reference
이 문제에 관하여(덜 알려진 JavaScript 트릭), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/bhagatparwinder/lesser-known-javascript-tricks-kjj텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)