티스토리 뷰
Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:
When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].
Example 1:
Input: nums = [[1,2],[3,4]], operation = "Add"
Output: 10
Explanation:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10
Example 2:
Input: nums = [[23,98,42,70]], operation = "String"
Output: "[23,98,42,70]"
Explanation:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // "[23,98,42,70]"
Example 3:
Input: nums = [[],[]], operation = "Add"
Output: 0
Explanation:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0
답:
1
var ArrayWrapper = function(nums) {
this.arrNumsToSum = nums.reduce((acc,cur) => acc + cur,0)
this.arrToString = `[${this.nums}]`
};
/**
* @return {number}
*/
ArrayWrapper.prototype.valueOf = function() {
return this.arrNumsToSum
}
/**
* @return {string}
*/
ArrayWrapper.prototype.toString = function() {
return this.arrToString
}
2
/**
* @param {number[]} nums
* @return {void}
*/
var ArrayWrapper = function(nums) {
this.nums = nums
};
/**
* @return {number}
*/
ArrayWrapper.prototype.valueOf = function() {
return this.nums.reduce((acc,cur) => acc + cur,0)
}
/**
* @return {string}
*/
ArrayWrapper.prototype.toString = function() {
return `[${this.nums}]`
}
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/
this와 prototype
javascript에서는 객체를 상속하기 위해 프로토타입이라는 방식을 사용한다.
var ArrayWrapper = function(nums) {
//속성과 메소드 정의
this.nums = nums
};
var obj1 = new ArrayWrapper();//인스턴스 생성
obj1.valueOf();
//기본 valueOf() 메서드는 this값 자체를 반환하고, 아직 객체가 아닌 경우 객체로 변환한다.
예시
const obj = {foo:1};
console.log(obj.valueOf === obj) //true
object.prototype.valueOf()
- object 인스턴스의 ValueOf() 메서드는 this값을 객체로 변환
- javascript는 객체를 원시값으로 변환하기 위해 valueOf 메서드를 호출
- 원시 값이 예상되는 객체를 만나면 자동으로 호출됨, 그렇기에 직접 메서드를 호출할 필요는 없음.(호출을 해도 되긴 함)
- 숫자 변환 및 기본 변환에 의해 우선적으로 호출됨
object.prototype.toString()
- object 인스턴스의 toString() 메서드는 객체를 나타내는 문자열을 반환함
- 사용자 지정 유형 강제 로직을 위해 파생 개체로 재정의될 수 있음.
- 객체를 원시값으로 변환하기 위해 toString 메서드를 호출, 원시 값이 예상되는 객체를 만나면 자동으로 호출함
- 문자열 변환에 의해 우선순위로 호출됨.
- "[object Type]"을 반환하며, 이는 객체 유형이다.
예시
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"
const toString = Object.prototype.toString;
//call 메서드를 사용하면 함수 호출 시 this 값을 명시적으로 설정할 수 있음
//toString 메서드는 this 값에 의존하기 때문에 다른 객체의 문맥에서 호출하면 해당 객체의 타입을 반환할 수 있음
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
'javascript > 알고리즘' 카테고리의 다른 글
[프로그래머스] 이진변환 반복하기 (0) | 2024.07.04 |
---|---|
[leetcode] 13. Roman to Integer (0) | 2022.04.06 |
[leetcode] 9. Palindrome Number (0) | 2022.03.25 |
[leetcode] 35. Search Insert Position (0) | 2022.01.24 |
[leetcode] 27. Remove Element (0) | 2022.01.22 |
- login연장
- 복수는 한번에 안댐
- httponly cookie
- debugger라도 해서 다풀어버리자
- 틀리면 말씀해주세요
- 한번에 받는건 id로 받기
- 지뢰찾기 게임도 못하는데
- 생성자함수에서의 this
- refresh token
- 무조건 비공개..
- 게임은 더못만든다
- 배열단순값 객체엔 속성값
- 문자열실수변경
- 무조곤 비공개
- var과 let의 차이
- 중복숫자찾기
- 메서드오버라이드
- MDN 참조
- 콜백함수에서의 this
- 객체의 참조값
- while문활용
- 이 쉬운걸 4시간동안....
- react 공식문서
- https://www.ncloud.com/support/notice/all/1424
- .fill
- NextJS13
- if문 중첩없애기
- 프로토타입 체인
- 화살표함수에서 this의 바인딩
- 타입스크립트 프로그래밍
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |