728x90

Maddy Osman, February 1, 2021

200Shares

TwitterFacebookLinkedInPinterestRedditBufferEmail

Facebook Instant Articles, introduced in 2015, is a mobile publishing format that enables news publishers to distribute articles through the Facebook app.

Try a free demo

Like Google AMP, these articles load and display 10x faster than the standard mobile web, creating a better user experience. Publishers were initially hesitant to comply with this new Facebook initiative, but those that were most interested in getting their content out to new audiences embraced this new content formatting system.

It certainly didn’t hurt that Facebook promised that they would help publishers earn from the content they published. Facebook would keep 100% of the advertising revenue for any ads they sold, and publishers could take 70% of whatever Facebook sold for them.

In order to get involved, all that publishers needed to do was adapt their articles to take on Facebook Instant Articles’ new formatting. Buzzfeed, Mashable, and Techcrunch are popular media sites that complied almost immediately. It’s possible to identify Facebook Instant Articles from those that aren’t thanks to the lightning bolt icon attached to the article preview.

Facebook instant articles (Image source: Facebook)

Using Facebook Instant Articles: Pros and Cons

Adapting existing content to a new format inevitably comes with challenges. Here are some of the greatest pros and cons associated with using Facebook Instant Articles with your WordPress website:

Facebook Instant Articles: Pros

  • Faster site load speed = an enhanced user experience.
  • Users may share your content more.
  • Gives publishers access to new monetization options.
  • Access to new audiences and increased reach.

Facebook Instant Articles: Cons 

  • Only displays your article: Facebook will not show anything that isn’t directly related to your article’s content, such as your important widgets or email signup forms.
  • Limits photos, videos, and ad blocks (though you can still use them with a little tinkering).
  • It presents yet another way a company is trying to serve up your own content. In other words, you have less control as people aren’t hitting your original site. People have expressed similar concerns with Google AMP.
  • You have to get manually approved by Facebook.

How to Format Facebook Instant Articles

There are several ways to format Facebook Instant Articles.

One way is to create Instant Article templates. That said, this method is for when you aren’t using WordPress or aren’t publishing articles through a third-party tool.

However, if you use WordPress or are publishing articles through a third-party tool, you can import your articles in 3 ways:

  • Facebook Instant Articles API
  • RSS feed
  • Supported third-party publishing tool, such as a Facebook Instant Articles WordPress plugin

If you’re using a Custom CMS, the first two methods are the way to go, but if you’re using CMS such as Drupal or WordPress and do not have a team of developers at your disposal, the last option (using a WordPress plugin) is best.  It enables independent publishers to make use of Facebook Instant Articles in the same way the big publishers do.

How to Setup Facebook Instant Articles for WordPress

WordPress is the largest CMS used in the world today and powers 33% of the web. Knowing this, Facebook decided to work with Automattic, the parent company of WordPress, to provide WordPress users with a free plugin to easily share content on Facebook in the Instant Articles format. However, we have seen some critical performance issues with the official plugin.

Facebook Instant Articles performance

Because of this, we recommend using an unofficial third-party plugin. In order to setup Facebook Instant Articles on your WordPress website, you’ll need:

Step 1

First thing’s first: visit the Facebook Instant Articles website and sign up.

Facebook Instant Articles website

Facebook will ask you to select a Facebook page for your website. Check the box to agree with the terms and then click on the ‘Access Instant Articles Tools’ button.

Access Instant Articles Tools

This will take you to the publisher tools on your Facebook page, which will now have an Instant Articles section.

Facebook Instant Articles publishing tools

Step 2

Prove ownership of your website by claiming your URL. Under “Instant Articles → Configuration → Tools → Connect Your Site” you will find your Page ID. Copy this to your clipboard.

Facebook Instant Articles connect site

Step 3

Download and install the WP Native Articles plugin on your WordPress site. This is not the official plugin, but the one we recommend if you’re concerned with performance.

One of the most useful and interesting features is content parsing, which corrects for some of the unstructured nature of WordPress content. By adding proper structure and formatting, WP Native Article’s content parsing feature helps content load even faster than the standard plugin offering. It also lets you integrate Google Analytics, ads, etc.

WP Native Articles WordPress plugin

Though the core WP Native Articles plugin is free, there’s a premium version available starting at $49 for a single site. The premium version comes with API syncing, advanced article analytics, and premium support if you run into any issues with deployment.

 

We grew our traffic 1,187% with WordPress.
We’ll show you how. 

Join 20,000+ others who get our weekly newsletter with insider WordPress tips!

Subscribe Now

Step 4

Take the Page ID you copied in Step 2 and paste it into the Authorization ID field of the WP Native Articles WordPress plugin.

Facebook Instant Articles authorization ID

Then click “Save Changes.”

Step 5 ★

After adding your page ID to the plugin settings, go back to the publisher tools on your Facebook page. Add your website URL below the code you copied earlier and then click on the claim URL button. Note: You might need to clear the cache on your WordPress site first for it to pick up the changes.

Claimed Facebook Instant Articles URL

If you receive the following error, it appears this is a known issue for some.

The provided URL is not being accepted because the site has minimal readership, which violates the Instant Article Policies (https://developers.facebook.com/docs/instant-articles/policy/). Please provide a different URL.

Here are a few tips on getting approved for Facebook Instant Articles:

  • Ensure you have a decent amount of content already on your WordPress site. Don’t try applying with a blank website.
  • Content can’t be behind a paywall.
  • Have a link to your site’s privacy policy visible.

Step 6

You should then style your Facebook posts to match the branding of your site. We recommend at least adding your logo and changing the colors. Go got the Facebook Publishing Tools and under “Instant Articles → Configuration → Tools → Styles” you can create and edit the default style.

Struggling with downtime and WordPress problems? Kinsta is the hosting solution designed to save you time! Check out our features

Facebook Instant Articles style editor

Step 7

The WordPress plugin will automatically generate an Instant Articles feed for your WordPress site. To get the feed URL, add the extension /feed/facebook-instant-articles/ after your website URL. You can also find this under the “Feed” tab in the WP Native Articles plugin.

For example: https://yourdomain.com/feed/facebook-instant-articles/

Facebook Instant Articles RSS feed

Copy that URL and switch back to the Facebook page Publishing Tools section. Then go to “Instant Articles → Configuration → Tools → Production RSS Feed”. Paste the URL there and save your changes.

Facebook Instant Articles production RSS Feed

It can take up to an hour for Facebook to ingest posts via the RSS Feed method.

Step 8

When Facebook has ingested 10 articles you can then submit them for review from the Configuration page. Reviews normally take 3-5 days and once approved your Instant Articles will be live. Any posts you share to your Facebook page will now automatically use the Instant Article version if it is available.

Facebook Instant Articles submit for review

Alternative Facebook Instant Article Plugins

As with any WordPress site, sometimes one plugin might work better than another with your current mix of installed plugins and your theme. If you have any issues with the already-mentioned plugin, you might want to also check out these other up and coming options:

LH Instant Articles

LH Instant Articles prides itself on creating “bloat free” Facebook Instant Articles thanks to the way it creates a Facebook-compliant RSS feed for your existing WordPress content.

LH Instant Articles WordPress plugin

Advanced functionality includes the ability to add related posts, analytics, and advertisements. Compared to some of the other options, it also claims to be easier to implement—making it ideal for someone who isn’t super handy with coding and troubleshooting.

Facebook Instant Articles for WordPress

The Facebook Instant Articles feature is helpful for both giant and independent publishers that want to reach new audiences with their content.

Being on Facebook’s Instant Articles platform (despite some backlash and publishers pulling out) can give you an extra advantage now that Facebook has introduced a new feature called Explore Feed (which allows you to discover content relevant to your interests). Furthermore, Instant Articles are easier to share than regular WordPress content, load faster, and integrate with Facebook for (perceived) higher prioritization in the news feed.

What are your thoughts? Have you given Facebook Instant Articles a try yet on your WordPress site?


If you enjoyed this article, then you’ll love Kinsta’s WordPress hosting platform. Turbocharge your website and get 24/7 support from our veteran WordPress team. Our Google Cloud powered infrastructure focuses on auto-scaling, performance, and security. Let us show you the Kinsta difference! Check out our plans

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