delete operator

WEB/JavaScript 2021. 8. 14. 20:28

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

Syntax

delete expression Copy to Clipboard

Where expression should evaluate to a property reference, e.g.:

delete object.property delete object['property'] Copy to Clipboard

Parameters

object

The name of an object, or an expression evaluating to an object.

property

The property to delete.

Return value

true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.

Exceptions

Throws TypeError in strict mode if the property is an own non-configurable property.

Description

Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. See the memory management page for more details.

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned.

However, it is important to consider the following scenarios:

  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true.
  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
  • Any property declared with var cannot be deleted from the global scope or from a function's scope.
    • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).
    • Functions which are part of an object (apart from the global scope) can be deleted with delete.
  • Any property declared with let or const cannot be deleted from the scope within which they were defined.
  • Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().

The following snippet gives a simple example:

var Employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete Employee.name); // returns true console.log(delete Employee.age); // returns true // When trying to delete a property that does // not exist, true is returned console.log(delete Employee.salary); // returns true Copy to Clipboard

Non-configurable properties

When a property is marked as non-configurable, delete won't have any effect, and will return false. In strict mode this will raise a TypeError.

var Employee = {}; Object.defineProperty(Employee, 'name', {configurable: false}); console.log(delete Employee.name); // returns false Copy to Clipboard

var, let, and const create non-configurable properties that cannot be deleted with the delete operator:

var nameOther = 'XYZ'; // We can access this global property using: Object.getOwnPropertyDescriptor(window, 'nameOther'); // output: Object {value: "XYZ", // writable: true, // enumerable: true, // configurable: false} // Since "nameOther" is added using with the // var keyword, it is marked as "non-configurable" delete nameOther; // return false Copy to Clipboard

In strict mode, this would have raised an exception.

Strict vs. non-strict mode

When in strict mode, if delete is used on a direct reference to a variable, a function argument or a function name, it will throw a SyntaxError. Therefore, to avoid syntax errors in strict mode, you must use the delete operator in the form of delete object.property or delete object['property'].

Object.defineProperty(globalThis, 'variable1', { value: 10, configurable: true, }); Object.defineProperty(globalThis, 'variable2', { value: 10, configurable: false, }); // SyntaxError in strict mode. console.log(delete variable1); // true // SyntaxError in strict mode. console.log(delete variable2); // false Copy to Clipboard

function func(param) { // SyntaxError in strict mode. console.log(delete param); // false } // SyntaxError in strict mode. console.log(delete func); // false Copy to Clipboard

Cross-browser notes

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

If you want to use an ordered associative array in a cross-browser environment, use a Map object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

Examples

// Creates the property adminName on the global scope. adminName = 'xyz'; // Creates the property empCount on the global scope. // Since we are using var, this is marked as non-configurable. The same is true of let and const. var empCount = 43; EmployeeDetails = { name: 'xyz', age: 5, designation: 'Developer' }; // adminName is a property of the global scope. // It can be deleted since it is created without var, // and is therefore configurable. delete adminName; // returns true // On the contrary, empCount is not configurable // since var was used. delete empCount; // returns false // delete can be used to remove properties from objects. delete EmployeeDetails.name; // returns true // Even when the property does not exist, delete returns "true". delete EmployeeDetails.salary; // returns true // delete does not affect built-in static properties. delete Math.PI; // returns false // EmployeeDetails is a property of the global scope. // Since it was defined without "var", it is marked configurable. delete EmployeeDetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } Copy to Clipboard

delete and the prototype chain

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

function Foo() { this.bar = 10; } Foo.prototype.bar = 42; var foo = new Foo(); // foo.bar is associated with the // own property. console.log(foo.bar); // 10 // Delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log(foo.bar); // 42 // Delete the property on the prototype. delete Foo.prototype.bar; // returns true // The "bar" property can no longer be // inherited from Foo since it has been // deleted. console.log(foo.bar); // undefined Copy to Clipboard

Deleting array elements

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; delete trees[3]; if (3 in trees) { // this is not executed } Copy to Clipboard

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees[3] = undefined; if (3 in trees) { // this is executed } Copy to Clipboard

If instead, you want to remove an array element by changing the contents of the array, use the splice() method. In the following example, trees[3] is removed from the array completely using splice():

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees); // ["redwood", "bay", "cedar", "maple"] Copy to Clipboard

Specifications

Specification

ECMAScript Language Specification (ECMAScript)
# sec-delete-operator

Browser compatibility

Report problems with this compatibility data on GitHub

desktopmobileserverChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on iOSSamsung InternetNode.jsdelete

 
 
Full support1
Full support12
Full support1
Full support4
Full support9
Full support1
Full support1
Full support18
Full support4
Full support10.1
Full support1
Full support1.0
Full support0.10.0

Legend

Full supportFull support

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

homes.sort(
   function(a, b) {          
      if (a.city === b.city) {
         // Price is only important when cities are the same
         return b.price - a.price;
      }
      return a.city > b.city ? 1 : -1;
   });

 

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

This was a small issue I came across recently and the solution I found was so brilliant I thought it was worth sharing on here.

So the problem was that I had an array like this:

 

var obj = [
    {
        "one": 1,
        "two": 9
    }, {
        "one": 3,
        "two": 5
    }, {
        "one": 1,
        "two": 2
    }
];

 

 

and I wanted to sort it by "one" and then by "two" to get a result like this:

var obj = [
    {
        "one": 1,
        "two": 2,
    }, {
        "one": 1,
        "two": 9
    }, {
        "one": 3,
        "two": 5
    }
];

 

sounds simple enough right? I thought so too, but the sorting algorithm that the browser is using limits your options when it comes to sorting by multiple fields. After a bit of researching I stumbled upon this wonderful solution: http://stackoverflow.com/questions/13211709/javascript-sort-array-by-multiple-number-fields

 

JavaScript sort array by multiple (number) fields

How can I implement a ORDER BY sort1 DESC, sort2 DESC logic in an JSON array like such: var items = '[ { "sort1": 1, "sort2": 3, "name" : "a", ...

stackoverflow.com

obj.sort(function(a, b) {
    return a["one"] - b["one"] || a["two"] - b["two"];
});

This will sort your array by "one" and if they are the same (ie. 0) then it will sort by "two". It's simple, concise, readable, and best of all - works perfectly.

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

자바스크립트의 2차원 배열이란?

  • 자바스크립트는 진정한 2차원 배열은 없다
  • var arr = [][]; 이와 같은 한 번에 2차원 배열 선언이 불가능하다
  • 약간의 트릭을 통하여 2차원 배열과 비슷한 배열을 만들 수 있다

아래의 예제 중 상황에 맞는 방법을 사용하면 된다

 

초기값을 할당하여 배열 생성

// arr[5][2]
var arr = [['a','b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']]; 

 

반복문을 사용하여 빈 배열 생성

// arr[5][2]
var arr = new Array(5);

for (var i = 0; i < arr.length; i++) {
    arr[i] = new Array(2);
}

 

2차원 배열 생성 함수를 만들어서 사용

function create2DArray(rows, columns) {
    var arr = new Array(rows);
    for (var i = 0; i < rows; i++) {
        arr[i] = new Array(columns);
    }
    return arr;
}

// arr[5][2]
var arr = create2DArray(5, 2);

 

Array 객체에 배열 생성 함수를 추가하여 사용

Array.matrix = function (m, n, initial) {
    var a, i, j, mat = [];
    for (i = 0; i < m; i += 1) {
        a = [];
        for (j = 0; j < n; j += 1) {
            a[j] = initial;
        }
        mat[i] = a;
    }
    return mat;
};

// matrix('행', '열', '기본값')
var arr = Array.matrix(5, 2, 0);

- 자바스크립트 핵심 가이드 (더글라스 크락포드) p109

 

ES6를 지원하는 최신 브라우저라면 사용 가능한 방법

// arr[5][2] (빈 배열 생성)
const arr1 = Array.from(Array(5), () => new Array(2)

// arr[5][2] (null로 초기화하여 생성)
const arr2 = Array.from(Array(5), () => Array(2).fill(null))

 

자바스크립트의 2차원 배열은 1차원 배열에 또 다른 배열 객체를 추가하여 2차원 배열 만드는 방법을 사용한다. 자바스크립트 배열의 특성을 잘 모른다면 조금 이상한 방법으로 보일 수도 있다.

자바스크립트의 배열은 동적으로 배열의 크기를 조절할 수 있으며, 배열에는 모든 유형의 변수 그리고 함수, 객체도 담을 수 있어서 유연하게 사용할 수 있지만 그만큼 충분히 이해를 하고 사용해야 한다.

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

In this article, we cover breakdown Bubble Sort and then also share its implementation in Javascript.

Firstly, let's get it out of the way. When we say "sort", the idea is to re-arrange the elements such that they are in ascending order.

If you are new to the concept of sorting, each section of the article would be useful - concept of bubble sort, its algorithms, efficiency, etc. However, If you are here to refresh your knowledge, jump straight to the javascript implementation of the sort. Go to code

Table of Contents

 

Explanation of Bubble Sort

If you are a newbie to sorting, Bubble sort is a great place to start! It is one of the more intuitive sorting methods as its algorithm mirrors how our brain generally thinks about sorting - by comparing.

Let's remove the vagueness and delve deeper into it.

A. What Bubble Sort Does?

To achieve sorting in Bubble Sort, the adjacent elements in the array are compared and the positions are swapped if the first element is greater than the second. In this fashion, the largest value "bubbles" to the top.

Usually, after each iteration the elements furthest to the right are in correct order. The process is repeated until all the elements are in their right position.

B. What Bubble Sort Does?

1. Starting with the first element, compare the current element with the next element of the array.

2. If the current element is greater than the next element of the array, swap them.

3. If the current element is less than the next element, just move to the next element.

4. Start again from Step 1.

C. Illustrating the Bubble sort method

Iteration 1: [6,4,2,5,7] → [4,6,2,5,7] → [4,2,6,5,7] → [4,2,5,6,7] → [4,2,5,6,7]

Iteration 2:[4,2,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7]

Iteration 3: [2,4,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7] → [2,4,5,6,7]

Other Alternatives

As you might have noticed, Bubble Sort only considers one element at a time. Thus, it is highly time consuming and inefficient. Due to its inefficiency, bubble sort is almost never used in production code.

You can use a built in function Array.prototype.sort() for sorting. This is an inplace algorithm just like bubble sort which converts the elements of the input array into strings and compares them based on their UTF-16 code unit values. Also, if you are interested, you can read about index sort which is another simple comparison based sort method that has a better performance than Bubble sort.

Implementing Bubble Sort using Javascript

Now as we have seen the logic behind bubble sort, we can write the code for it in a straightforward manner, using two nested loops.

 

 

let bubbleSort = (inputArr) => {
    let len = inputArr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (inputArr[j] > inputArr[j + 1]) {
                let tmp = inputArr[j];
                inputArr[j] = inputArr[j + 1];
                inputArr[j + 1] = tmp;
            }
        }
    }
    return inputArr;
};

As you can see here, the sorting function will run until the variable "i" is equal to the length of the array. This might not be the most efficient solution as it means the function will run on an already sorted array more than once.

A slightly better solution involves tracking a variable called "checked" which is initially set to FALSE and becomes true when there is a swap during the iteration. Running this code on a do while loop to run the sorting function only when "checked" is true ensures that the function will not run on a sorted array more than once.

 

 

let bubbleSort = (inputArr) => {
    let len = inputArr.length;
    let checked;
    do {
        checked = false;
        for (let i = 0; i < len; i++) {
            if (inputArr[i] > inputArr[i + 1]) {
                let tmp = inputArr[i];
                inputArr[i] = inputArr[i + 1];
                inputArr[i + 1] = tmp;
                checked = true;
            }
        }
    } while (checked);
    return inputArr;
 };

 

Visualization

If you are finding it hard to visualize Bubble Sort, you can check this website https://visualgo.net/bn/sorting?slide=1.

You can play around with the code and see the specific function of each part of the code and how they play together to get the final sorted array.

Complexity of Bubble Sort

The worst case scenario: quadratic O(n²): this is the case when every element of the input array is exactly opposite of the sorted order.

Best case scenario: linear O(n): when the input array is already sorted. Even in this case, we have to iterate through each set of numbers once.

The space complexity of Bubble Sort is O(1).

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

 

 

charAt()

charAt 은 문자열에서 인자로 주어진 값에 해당하는 문자를 리턴합니다.

 

문법

JAVASCRIPT

charAt(index)

Copy

 

인자

  • index - 필수
  • 0보다 큰 정수

 

 

설명(description)

문자열에 속하는 문자는 왼쪽부터 오른쪽까지 0부터 인덱싱되어 있습니다. 

charAt은 index로 주어진 값에 해당하는 문자를 리턴합니다. 

인덱스는 0부터 시작하기 때문에 index로 들어갈 수 있는 가장 큰 수는 (문자열.legnth-1)이다. 존재하지 않는 index를 인자로 전달하면 공백이 출력됩니다.

charAt 는 index에 해당하는 문자를 리턴하고, chartCodeAt은 유니코드 값을 리턴하는 차이가 있다.

 

예제 코드

JAVASCRIPT

charAt(index)

 

 

 

charCodeAt()

charCodeAt 메서드는 index에 해당하는 문자의 unicode 값을 리턴합니다.

 

문법(Syntax)

JAVASCRIPT

string.charCodeAt(index)

Copy

 

인자

  • ndex - 필수
  • 0보다 큰 정수

 

설명(description)

유니코드는 모든 시스템에서 일관되게 문자를 표현하기 위한 산업표준입니다. 

charCodeAt은 주어진 index에 해당하는 유니코드 값을 리턴하는데 이 값은 unicode가 지원되는 모든 시스템에서 동일한 문자를 가르킵니다. 

charAt는 index에 해당하는 문자를 리턴하고, chartCodeAt은 유니코드 값을 리턴하는 차이가 있습니다.

 

예제 코드

JAVASCRIPT

var stringName = '자바스크립트'; console.log(stringName.charCodeAt(0)); // 51088 // http://www.unicode.org/charts/PDF/UAC00.pdf 에서 '자'을 찾아보면 'C790'인데 이것은 16진수다. // 이를 10진수로 변환하면 51088 된다.

Copy

 

 

참고 관련 링크

  1. 유니코드
  2. 한글에 대한 유니코드

 

 

 



출처: https://webclub.tistory.com/329 [Web Club]

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

 

Class


ES6에서 class 라는 문법이 추가 되었고, 기존의 prototype 기반으로 클래스를 만드는 것보다 명료하게 클래스를 만들 수 있게 되었습니다.

 

 

1. 클래스 정의

ES6에서 클래스는 특별한 함수입니다. 그렇기 때문에, 함수와 동일하게 클래스 선언(Class declarations)과 클래스 표현(Class expressions)으로 클래스를 만들 수 있습니다 ([자바스크립트] 함수(Function), 즉시실행함수(Immediately-invoked function expression) 참고)

 

클래스 선언(Class declarations)

class Polygon { constructor(height, width) { this.height = height; this.width = width; } }

클래스 선언은 함수 선언과 달리 호이스팅 되지 않습니다. ([자바스크립트] 유효범위(Scope)와 호이스팅(Hoisting) 참고)

var p = new Polygon(); // ReferenceError class Polygon {}

클래스 선언은 호이스팅 되지 않습니다.

 

클래스 표현(Class expressions)

익명 클래스와 기명 클래스를 만들 수 있습니다.

// unnamed var Polygon = class { constructor(height, width) { this.height = height; this.width = width; } }; // named var Polygon = class Polygon { constructor(height, width) { this.height = height; this.width = width; } };

클래스 표현(Class expressions) 또한 클래스 선언(Class declarations)와 같이 호이스팅(hoisting)이 되지 않습니다.

 

 

2. 메소드 정의

ES6의 class에서, 클래스의 몸통(body)는 {} 이며, class 메소드는 class의 {} 안에 정의해야 합니다.

 

Strict mode

클래스 몸통(body)는 strict mode로 실행됩니다. ([자바스크립트] 엄격 모드(strict mode) 참고)

 

생성자(Constructor)

생성자 메소드는 객체의 생성과 초기화를 하는 특별한 메소드입니다. 클래스에서 constructor 이름을 갖는 메소드는 하나여야 합니다.

var Polygon = class { constructor(height, width) { this.height = height; this.width = width; } constructor(height2, width2) { this.height = height2 * 2 ; this.width = width2 * 2; } };

constructor는 하나여야 합니다.

 

생성자 메소드에서 super 키워드를 통해 상위 클래스의 생성자 메소드를 호출 할 수 있습니다.

class Polygon { constructor(height, width) { this.height = height; this.width = width; } } class Square extends Polygon { constructor(length) { // length로 다각형의 넓이와 높이를 정의하기 위해 부모클래스의 생성자를 호출합니다. super(length, length); // Note: 파생 클래스에서, 'this'를 사용하기 전에는 반드시 super()를 // 호출하여야 합니다. 그렇지 않을 경우 참조에러가 발생합니다. this.name = 'Square'; } get area() { return this.height * this.width; } set area(value) { this.area = value; } } var test = new Square(4); console.log(test.area);

생성자 메소드에서 this를 사용하기 위해서 super 메소드를 먼저 호출해야 합니다.

set, get 함수의 선언법은 [자바스크립트] getter, setter 참고바랍니다.

 

프로토타입 메소드(Prototype methods)

class Polygon { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } } const square = new Polygon(10, 10); console.log(square.area);

 

ES6는 메소드 정의를 위한 더 짧은 구문이 도입되었습니다. 다음 코드가 주어지면,

var obj = { foo: function() {}, bar: function() {} };

ES6에서는 아래와 같이 줄일 수 있습니다.

var obj = { foo() {}, bar() {} };

 

정적 메소드(static methods)

static 메소드는 클래스의 인스턴스 (var a = new testFunc()) 필요없이 호출 가능합니다. 또한 클래스의 인스턴스에서 static 메소드를 호출 할 수 없습니다.

class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); console.log(Point.distance(p1, p2)); var p3 = new Point(1, 1); p3.distance(p1, p2);

class의 static 메소드

 

인스턴스 없이 정상적으로 distance가 호출 되는 것과, 인스턴스를 통해 distance를 호출 할 때 TypeError가 발생하는 것을 확인 할 수 있습니다.

 

 

오토박싱(Autoboxing)

autoboxing이란?

일반 함수에서 this는 window 객체를 가르키게 됩니다. this가 window 객체 (global object)를 가르키는 이유는 autoboxing 덕분입니다.

non-strict 모드에서 ([자바스크립트] this의 정체 참고) this 값이 null 혹은 undefined 일 경우 window 객체(global object)로 자동으로 변환해 주는 것을 autoboxing이라고 합니다.

 

프로토타입 기반의 클래스에서 autoboxing

프로토타입 기반의 class의 경우

function Animal() { } Animal.prototype.speak = function(){ console.log(this); return this; } Animal.eat = function() { console.log(this); return this; } let obj = new Animal(); let speak = obj.speak; speak(); // global object let eat = Animal.eat; eat(); // global object

프로토타입 기반의 클래스의 autoboxing

 

autoboxing이 되어, 일반 함수를 호출하는 것처럼 메소드를 호출 한 경우 window 객체(global object)를 출력하는 것을 확인 할 수 있습니다.

 

ES6의 클래스 기반의 autoboxing

ES6의 class에서는 autoboxing이 되지 않습니다.

class Animal { speak() { console.log(this); return this; } static eat() { console.log(this); return this; } } let obj = new Animal(); let speak = obj.speak; speak(); // undefined obj.speak(); let eat = Animal.eat; eat(); // undefined Animal.eat();

ES6의 class는 autoboxing이 안됨

 

autoboxing이 되지 않아, 일반 함수를 호출하는 것처럼 메소드를 호출 한 경우 undefined가 출력되는 것을 확인 할 수 있습니다.

그렇기 때문에 ES6의 클래스에서 메소드를 변수에 저장하여 사용할 경우, this에 유의해서 사용해야 합니다.

 

 

3. 클래스 상속(sub classing)

ES6의 클래스 상속

extends 키워드를 통하여 클래스를 상속 받아, 자식 클래스를 만들 수 있습니다.

class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } } var d = new Dog('Mitzie'); d.speak();

ES6의 클래스 상속

 

프로토타입 기반의 클래스 상속

프로토타입 기반의 클래스도 extends 키워드를 통해 상속 할 수 있습니다.

function Animal (name) { this.name = name; } Animal.prototype.speak = function () { console.log(this.name + ' makes a noise.'); } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } } var d = new Dog('Mitzie'); d.speak();

프로토타입 기반의 클래스 상속

 

일반 객체의 클래스 상속

일반 객체는 extends 키워드를 통해 상속할 수 없습니다. 상속하고 싶다면 Object.setPrototypeOf 메소드를 사용하여 상속해야 합니다.

var Animal = { speak() { console.log(this.name + ' makes a noise.'); } }; class Dog { constructor(name) { this.name = name; } speak() { console.log(this.name + ' barks.'); } } Object.setPrototypeOf(Dog.prototype, Animal); var d = new Dog('Mitzie'); d.speak();

일반 객체의 클래스 상속

 

 

4. Species

class MyArray extends Array { // 부모 Array 생성자로 종류 덮어쓰기 static get [Symbol.species]() { return Array; } } var a = new MyArray(1,2,3); var mapped = a.map(x => x * x); console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // true

Symbol.species

 

Array를 상속받은 MyArray에서 Array의 default 생성자를 덮어 쓰고 싶을 경우, Symbol.species를 사용하면 됩니다. (get []의 문법은 [자바스크립트] getter, setter 참고 바랍니다.)

Symbol.species로 Array의 생성자를 가져오고, get [] 로 Array를 리턴함으로 부모 Array의 생성자를 덮어 쓸 수 있습니다.

 

 

5. super로 부모 클래스 호출하기

super 키워드를 홈하여 부모 클래스의 메소드를 호출 할 수 있습니다.

 

프로토타입 기반의 부모 클래스 메소드 호출

function Cat(name) { this.name = name; } Cat.prototype.speak = function () { console.log(this.name + ' makes a noise.'); }; function Lion(name) { // `super()` 호출 Cat.call(this, name); } // `Cat` 클래스 상속 Lion.prototype = new Cat(); Lion.prototype.constructor = Lion; // `speak()` 메서드 오버라이드 Lion.prototype.speak = function () { Cat.prototype.speak.call(this); console.log(this.name + ' roars.'); }; var lion = new Lion("BIG"); lion.speak();

프로토타입 기반의 부모 클래스 메소드 호출

 

프로토타입 기반의 클래스에서 부모 클래스의 메소드를 호출하기 위해서 call과 같은 함수를 사용해야 합니다. ([자바스크립트] API - call, apply 함수 참고)

 

ES6 클래스 기반의 부모 클래스 메소드 호출

class Cat { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Lion extends Cat { speak() { super.speak(); console.log(this.name + ' roars.'); } } var lion = new Lion("BIG"); lion.speak();

ES6 클래스 기반의 부모 클래스 메소드 호출

 

ES6 클래스는 super 메소드를 사용하여 부모 클래스의 메소드를 호출 할 수 있습니다.



출처: https://beomy.tistory.com/15 [beomy]

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

The String object's charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

 

Syntax

let character = str.charAt(index)

Parameters

indexAn integer between 0 and str.length - 1. If the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned.

Return value

A string representing the character (exactly one UTF-16 code unit) at the specified index. If index is out of range, charAt() returns an empty string.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character—in a string called stringName—is stringName.length - 1. If the index you supply is out of this range, JavaScript returns an empty string.

If no index is provided to charAt(), the default is 0.

Examples

Displaying characters at different locations in a string

The following example displays characters at different locations in the string "Brave new world":

var anyString = 'Brave new world';
console.log("The character at index 0   is '" + anyString.charAt()   + "'");
// No index was provided, used 0 as default

console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");

These lines display the following:

 

The character at index 0   is 'B'

The character at index 0   is 'B'
The character at index 1   is 'r'
The character at index 2   is 'a'
The character at index 3   is 'v'
The character at index 4   is 'e'
The character at index 999 is ''

 

 

Getting whole characters

The following provides a means of ensuring that going through a string loop always provides a whole character, even if the string contains characters that are not in the Basic Multi-lingual Plane.

var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
  if ((chr = getWholeChar(str, i)) === false) {
    continue;
  }
  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning a variable to represent the
  // individual character

  console.log(chr);
}

function getWholeChar(str, i) {
  var code = str.charCodeAt(i);

  if (Number.isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return str.charAt(i);
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i + 1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return str.charAt(i) + str.charAt(i + 1);
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i - 1);

  // (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate';
  }
  // We can pass over low surrogates now as the second component
  // in a pair which we have already processed
  return false;
}

In an ECMAScript 2016 environment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automatically (if the character warrants it in being a surrogate pair).

let str = 'A\uD87E\uDC04Z'  // We could also use a non-BMP character directly
for (let i = 0, chr; i < str.length; i++) {
  [chr, i] = getWholeCharAndI(str, i)

  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning an array with the individual character
  // and 'i' value (only changed if a surrogate pair)

  console.log(chr)
}

function getWholeCharAndI(str, i) {
  let code = str.charCodeAt(i)

  if (Number.isNaN(code)) {
    return ''  // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return [str.charAt(i), i]  // Normal character, keeping 'i' the same
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate'
    }
    let next = str.charCodeAt(i + 1)
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate'
      }
      return [str.charAt(i) + str.charAt(i + 1), i + 1]
  }

  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate'
  }

  let prev = str.charCodeAt(i - 1)

  // (could change last hex to 0xDB7F to treat high private surrogates
  // as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate'
  }

  // Return the next character instead (and increment)
  return [str.charAt(i + 1), i + 1]
}

Fixing charAt() to support non-Basic-Multilingual-Plane (BMP) characters

While the previous example may be more useful for programs that must support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following:

function fixedCharAt(str, idx) {
  let ret = ''
  str += ''
  let end = str.length

  let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
  while ((surrogatePairs.exec(str)) != null) {
    let lastIdx = surrogatePairs.lastIndex
    if (lastIdx - 2 < idx) {
      idx++
    } else {
      break
    }
  }

  if (idx >= end || idx < 0) {
    return ''
  }

  ret += str.charAt(idx)

  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
    // Go one further, since one of the "characters" is part of a surrogate pair
    ret += str.charAt(idx + 1)
  }
  return ret
}
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요