javascript의 string method를 더 잘 알아보기 위해 직접 구현후 테스트코드를 짰다.
이 기록은 구현 중 알게 된 것을 모아둔 것이다.
https://github.com/rami0617/learn-js
GitHub - rami0617/learn-js: To study javascript, I implement the methods myself by referring to the MDN documentation.
To study javascript, I implement the methods myself by referring to the MDN documentation. - rami0617/learn-js
github.com
call method
1. 'this'값을 명시적으로 설정하고 원하는 문맥(context)에서 함수를 실행하기 위해서.
2. 함수가 호출되는 환경을 제어할 수 있고, 객체 간에 메소드를 공유하거나 재사용할 수 있는 유연성을 제공함.
functionName.call(thisArg, arg1, arg2, ...);
//thisArg : 함수 내부에서 'this'로 사용할 값.
//만약 'thisArg'를 제공하지 않으면 기본적으로 'undefined'가 사용됨.
//전역객체('window' 또는 'global')가 this로 설정됨.
- this 값 제어
call 메소드는 함수 호출 시 'this'값을 명시적으로 설정할 수 있어, 특정 문맥에서 함수가 동작할 수 있습니다.
const person = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name);
}
};
const anotherPerson = {
name: 'Bob'
};
person.greet.call(anotherPerson); //Hello, Bob
- 함수 재사용
function introduce(language) {
console.log(`My name is ${this.name} and I speak ${language}`);
}
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };
introduce.call(person1, "English"); //My name is Alice and I speak English
introduce.call(person2, "Spanish"); //My name is Bob and I speak Spanish
- 객체 상속 없이 메소드 사용
const dog = {
sound: "Woof",
speak : function () {
console.log(this.sound);
}
};
const cat = {
sound: "Meow"
};
dog.speak.call(cat); //Meow
- 인수 전달
call 메소드는 함수 호출 시 여러 인자들을 명시적으로 전달할 수 있음.
function sum(a, b) {
return a + b;
}
console.log(sum.call(null, 3, 5)); //8
Object.is()
인자로 받는 2개의 value가 같은지 확인해 준다.
NaN일 때 예외처리를 하려고 하는데 isNaN 메소드를 사용할 경우 number가 인자로 들어갈 경우 true로 반환되는데, 내가 원하는 동작은 NaN을 가려내는 것이었고, Object.is를 사용하면 정확하게 NaN인 경우만 추려낼 수 있다는 것을 알게 되었다.
Array.prototype.lastIndexOf = function (
searchElement: any,
fromIndex?: number
) {
// if(isNaN(serachElement)) return -1;
if (Object.is(searchElement, NaN)) return -1;
//searches from the alst index and returns the first element equal to searchElement
let newFromIndex = fromIndex === undefined ? this.length - 1 : fromIndex;
if (newFromIndex < 0) {
newFromIndex = Math.max(this.length + fromIndex, 0);
}
for (let i = newFromIndex; i >= 0; i--) {
if (this[i] === searchElement) {
return i;
}
}
return -1;
};
map vs forEach & for ~ of
map은 새로운 배열을 return 하고, forEach, for ~ of는 하지 않는다.
만약 callback의 결과값을 새로운 배열로 받아서 사용하는게 아니라면 map을 사용하기보다 forEach나 for ~ of를 사용하는 것이 좋다.
map을 사용하면서 반환된 배열을 무시하면 메모리와 성능측면에서 불필요한 오버헤드가 발생할 수 있다.
희소배열 vs 밀집배열
희소 배열(Sparse Array)
- 배열의 요소들 중 일부가 정의되지 않은 배열을 말함. 배열의 길이는 길지만 실제 값이 정의된 요소는 적은 경우.
특징
1. 정의되지 않은 요소 : 희소 배열은 중간에 값이 없는 요소들이 있음. 이런 요소들은 'undefined'와는 달리 아예 존재하지 않음.
2. 메모리 효율성 : 메모리를 덜 차지할 수 있음. 정의되지 않은 요소는 메모리를 사용하지 않음.
3. 길이 속성 : 배열의 길이는 전체 인덱스의 최대값 보다 큽니다.
const sparseArray = [];
sparseArray[0] = 'a';
sparseArray[3] = 'e';
console.log(sparseArray); //['a', empty x 2, 'e']
console.log(sparseArray.length); //4
밀집 배열(Dense Array)
- 배열의 모든 요소들이 연속적으로 정의돈 배열. 배열의 각 인덱스가 값이나 'undefined'로 채워져 있음.
특징
1. 정의된 요소 : 모든 인덱스가 값 또는 'undefined'로 정의되어 있음.
2. 메모리 사용 : 배열의 모든 인덱스가 메모리를 사용함.
3. 길이 속성: 배열의 길이는 실제 요소의 수와 일치함.
* 밀집 배열에서 undefined 값과 정의되지 않은 값의 차이점.
undefined
- 정의됨 : 'undefined' 값은 배열의 특정 인덱스에 값이 존재하긴 하지만 그 값이 'undefined'로 설정된 상태를 의미함.
- 명시적 설정 가능 : 배열의 특정 요소를 명시적으로 'undefined'로 설정할 수 있음.
- forEach와 for ~ of에 포함 : 배열의 모든 요소를 순회할 때 forEach, for ~ of 루프에 포함됨.
정의되지 않은 값
- 정의되지 않음 : 배열의 특정 인덱스가 아예 정의되지 않은 상태를 의미함. 즉, 그 인덱스에 아무런 값이 설정되지 않은 상태를 의미함.
- 명시적 설정 불가 : 명시적으로 설정할 수 있는 값이 아님. 이는 배열을 생성할 때 특정 인덱스를 건너뛰면 발생함.
- forEach와 for ~of에 포함되지 않음 : 배열을 순회할 때 forEach, for ~ of 루프에서 포함되지 않음.
const array1 = [1, undefined, 2];
const array2 = [1, , 2];
array1.forEach((ele) => {
console.log(ele); //1, undefined, 2
});
array2.forEach((ele) => {
console.log(ele); //1, 2
});
reverse vs toReversed , sort vs toSorted, splice vs toSplice
reverse, sort, splice는 in-place algorithm을 사용하여 원본 배열을 변경하지만, toReversed, toSorted, toSplice는 새로운 배열을 만들어 return 한다.
원본 배열을 유지하면서 reverse, sort, splice를 사용하길 원할 경우 toReversed, toSorted, toSplice 메소드를 사용하면 된다.
'javascript' 카테고리의 다른 글
FOUT(Flash of Unstyled Text) (0) | 2025.01.13 |
---|---|
[LEARN-JS] Array method - 기존 배열 변경 유무에 따라 나누기 (0) | 2024.08.12 |
[LEARN-JS] String, Jest (0) | 2024.07.23 |
closure (0) | 2024.03.27 |
scope (1) | 2024.03.26 |