728x90

 

 

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]

728x90

 

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]

728x90

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
}
728x90

오늘은 JavaScript의 형변환에 대해서 알아보겠습니다. 하는 법이 있다는 것은 알고있는데 머리에 다 담고 살기는 너무 어려운 것 같습니다. 그러니 공부방에 정리해 놓아야 겠습니다.

 

 

일단 먼저 자바스크립트에서 변수를 선언하는 것부터 알아보겠습니다.

 

var 변수 = 10;

 

위에서 선언한 내용은 변수를 숫자 10으로 선언하는 것입니다.

 

var 변수 = "10";

 

얼핏보면 같은 것으로 생각 할수도 있지만 언어를 공부하신 분이라면 다들 눈치 채셨을 겁니다. 이번엔 변수를 문자열 10으로 선언하는 것입니다.

 

기존의 Java 같은 경우는 int 변수, String 변수 등 해당하는 형으로 선언하는 것이 맞지만 자바스크립트는 조금 다릅니다. 일단 모든 변수를 var로 선언 가능합니다.

 

- 문자형을 숫자형으로 변환하기

 

var 변수 = parseInt(문자);    //문자를 정수형 숫자로 변환해줌

var 변수 = parseFloat(문자);     //문자를 실수형 숫자로 변환해줌

var 변수 = Nember(문자);    //문자를 정수&실수형 숫자로 변환해줌

 

예제)

var x = "999";    //문자형 999

var y = "99.99";    //문자형 99.99

var a = parseInt(x);    //숫자형 정수 999

var b = parseInt(y);    //숫자형 정수 99

var a = parseFloat(x);    //숫자형 실수 999

var b = parseFloat(y);    //숫자형 실수 99.99

var a = Number(x);    //숫자형 정수 999

var b = Number(y);    //숫자형 실수 99.99

 

var x = "a999";    //문자형 a999

var y = "a99.99";    //문자형 a99.99

var a = parseInt(x);    //숫자형 NaN

var b = ParseInt(y);    //숫자형 NaN

var a = parseFloat(x);    //숫자형 NaN

var b = parseFloat(y);    //숫자형 NaN

var a = Number(x);    //숫자형 NaN

var b = Number(y);    //숫자형 NaN

 

※ 문자열 맨앞에 문자로 시작하면 형변환을 해도 값을 인식하지 못한다.

 

var x = "999a9";    //문자열 999a9

var y = "99.9a9";    //문자열 99.9a9

var a = parseInt(x);    //숫자형 999

var b = parseInt(y);    //숫자형 99

var a = parseFloat(x);    //숫자형 999

var b = parseFloat(y);    //숫자형 99.9

var a = Number(x);    //숫자형 NaN

var b = Number(y);    //숫자형 NaN

 

- 숫자형을 문자형으로 변환하기

 

 

var 변수 = String(숫자);    //숫자를 문자로 변환해줌

var 변수 = 숫자.toString(진법);    //숫자를 문자로 변환해줌 - 변환하면서 진법을 바꿀 수 있음

var 변수 = 숫자.toFixed(소수자리수);    //숫자를 문자로 변환해줌 - 실수형의 소수점 자리를 지정할 수 있음

var 변수 = 숫자 + "문자열";    //숫자와 문자열을 한 문자열로 더해줌

 

var x = 123;    //숫자형 123

var a = String(x);    //문자형 123

var a = x.toString();    //문자형 123

var a = x.toString(2);    //문자형 1111011(2진법)

var a = x.toString(16);    //문자형 7b(16진법)

var a = x.toFixed();    //문자형 123

var a = x.toFixed(1);    //문자형 123.0

 

var y = 99.999;    //숫자형 99.999

var a = x.toFixed();    //문자형 99

var a = x.toFixed(1);    //문자형 99.9

var a = x.toFixed(3);    //문자형 99.999

var a = x.toFixed(4);    //문자형 99.9990

 

확률을 표현해줄 때 유용하다.

 

var z = 9;    //숫자형 9

var a = a + "ElNino Torres";    //문자형 9ElNino Torres

 

이정도만 알고 있어도 자바스크립트를 사용하는데 편리할 듯 싶습니다. 추후에 기회가 되면 다른 메소드들도 알아보도록 해야겠습니다.

+ Recent posts