Io.js Introduction (iii)--supported ES6 (bottom)

Source: Internet
Author: User
Tags string methods unique id

(connected to the previous article)

Standard ES6 Features

6. The new string method/new string methods

7. Symbol/symbols

8. String Template/template Strings

The new string method/new string methods

Codepointat () and string.fromcodepoint ()
JS interior is in the form of UTF-16 (each character length is fixed to 16 bits, 2 bytes) to store character encoding. In terms of Chinese characters, most of the Chinese characters are stored in 2-byte form, but some Chinese characters need to have 4 bytes of length to store (its codepoint/code point is greater than 0xFFFF), such as the uncommon word "??" (Note that it is not "Kat"), its Unicode code point is 0x20bb7 (decimal is 134071), UTF-16 code point is 0xd842 0xdfb7 (decimal 55362 57271).
If we use regular charAt (0) and String.fromCharCode () for this character, we will not get the correct code point/character:

var s = "??" ,       = S.charcodeat (0),  //55362, which is the first two bytes of code point   b = String.fromCharCode (0x20bb7);  // garbled characters

To solve this problem, ES6 introduced the two string methods of Codepointat () and String.fromcodepoint (), which can obtain the Unicode code point of a character successfully, which can be obtained by a known code point:

var s = "??" ,     = S.codepointat (0),  //134071    b = string.fromcodepoint (0x20bb7);  // "??"

The test of this method is cumbersome because the command line interface is GBK encoded, even if the "chcp 65001" password is cut into the UTF-8 form, it is not possible to display the uncommon characters mentioned above correctly. But we can go to the browser (not IE) to display the code:

vars = "??", a= S.codepointat (0), AA= S.charcodeat (0), B= S.codepointat (1), BB= S.charcodeat (1), C=String.fromcodepoint (a), CC=String.fromCharCode (AA), D=String.fromcodepoint (b), DD=String.fromCharCode (BB); Console.log ("A:" +a+ ", aa:" +aa+ ", B:" +b+ ", BB:" +bb+ ", C:" +c+ ", cc:" +cc+ ", D:" +d+ ", DD:" +dd);varHTTP = require (' http '), FS= Require (' FS '); Http.createserver (function(req,res) {Res.writeheader (200,{"Content-type": "Text/html"}); Res.write (' <!doctype html>); Res.write ("A:" +a+ ", aa:" +aa+ ", B:" +b+ ", BB:" +bb+ ", C:" +c+ ", cc:" +cc+ ", D:" +d+ ", DD:" +DD); Res.end ("</div></body>);}). Listen (1337);
View Code

Then we visit address http://127.0.0.1:1337/to see the following:

StartsWith (), EndsWith () and includes ()
General we will use S.indexof () to detect whether a string contains a string. ES6 provides 3 new string retrieval methods, where StartsWith () and EndsWith () are used to match string fragments starting at the head/tail, and includes () have no positional qualification, and they all return a Boolean value. These three methods are well understood, directly on the example bar:

var str = ' to was ', or not to be, which is the question. ' ; Console.log (Str.startswith (' to be '));   // trueconsole.log (Str.endswith (' question. '));   // trueconsole.log (Str.includes (' Not to IS '));   // true

Each of the three methods supports the second parameter, which indicates where to start the search:

var str = ' to was ', or not to be, which is the question. ' ; Console.log (Str.startswith (' to be ', 1));   // falseConsole.log (Str.endswith (' to ', 2));   // trueconsole.log (Str.includes (' Not to is ', 1));   // true

Note EndsWith (), followed by the second argument, represents a string that matches the end of the position from the start to the parameter index.

Repeat ()
Repeat () returns a new string indicating that the original string is repeated n times:

var str = "x". Repeat (3//XXX

Normalize ()
This method converts the given string to Unicode normalized characters:

var // ??

Here's an interesting example: Unicode provides two ways to represent intonation and accent marks. One is to provide directly accented characters, such as Ǒ (\U01D1). The other is to provide a synthetic symbol (combining character), which is the composition of the original character and the accent symbol, two words conform to a character, such as O (\u004f) and (\u030c) synthesis ǒ (\u004f\u030c).
Both of these representations are visually and semantically equivalent, but JavaScript does not recognize:

// false // 1 // 2

The code above indicates that JavaScript treats synthetic characters as two characters, resulting in unequal representation of two methods. Use the normalize () method to resolve the problem:

var n1 = ' \u01d1 'var n2 = ' \u004f\u030c '//True Note this is only true in Chrome, but is false in Iojs, because IOJS does not have its own intl by default , children's shoes that need to be installed can be viewed here   

The normalize method can accept four parameters:

NFC, the default parameter, represents the "standard equivalent composition" (Normalization Form Canonical composition), which returns the composite characters of multiple simple characters. The so-called "standard equivalence" refers to the visual and semantic equivalence.
NFD, which represents the "standard equivalent decomposition" (Normalization Form Canonical decomposition), which returns multiple simple characters for synthetic character decomposition, on the premise of standard equivalence.
NFKC, which represents "compatible equivalent synthesis" (Normalization Form compatibility composition), returns the synthetic character. The so-called "compatible equivalence" refers to the semantic existence of equivalence, but not visually equivalent, such as "DB" and "Hei XI" (Of course, here is just an example, normalize only apply to European text, to solve the problem of French accent).
NFKD, which means "compatible equivalent decomposition" (Normalization Form compatibility decomposition), which returns multiple simple characters of the synthetic character decomposition, on the premise of compatibility equivalence.

// 1 // 2

Symbol/symbols

Codepointat () and string.fromcodepoint ()

ES6 introduces a new primitive data type, symbol, that represents a unique ID. It is generated by the symbol function:

var symbol1 = symbol (); Console.log (typeof symbol);  // "Symbol"

The symbol function can accept a string as a parameter, representing the name of the symbol instance. It is important to note that the symbol instances are unique and unequal:

var symbola = Symbol (' Test '); var symbolb = Symbol (' Test '); Console.log (Symbola//false

Note that you cannot use the new command before the symbol function, or you will get an error. This is because the generated symbol is a value of the original type, not an object. If you really want to create a symbol wrapper object, you should use the object () method:

var sym = Symbol ("foo"); typeof Sym;     //  var symobj = Object (sym); typeof Symobj;  // "Object"

We use the symbol instance as the property name of an object because it is unique and can effectively prevent object properties from being contaminated:

var syma = Symbol (' test '); var symb = Symbol (' test '); var aag == 123= 456; Console.log (Aag[syma]);   // 123

Another need to know is that the symbol instances are not enumerated as object properties, but we can get them by Object.getownpropertysymbols () :

varSyma = Symbol (' A ');varSYMB = Symbol (' B ');varobj ={};obj[syma]= 123; OBJ[SYMB]= 456; obj["C"] = 789; for(varIinchobj) console.log (i+ ":" +obj[i]);//output only "c:789"varObjectsymbols =object.getownpropertysymbols (obj); Console.log (objectsymbols.length);//2Console.log (Objectsymbols[0]);//Symbol (a) for(varIinchobjectsymbols) Console.log (i+ ":" + objectsymbols[i].tostring ());//Note the use of the. toString () method to convert the symbol instance to a string//0:symbol (a)//1:symbol (b)

In addition to the usual creation of unique symbol instances, we can also create shareable symbol instances with symbol.for (). With the Symbol instance created by Symbol.for (), we can use Symbol.keyfor () to get its key name:

var syma = Symbol (' a '); var symaa = Symbol (' a '); var symb = Symbol.  for (' B '); var symbb = Symbol.  for (' B '); Console.log (Syma//false//true//B 

In addition to being a unique, non-enumerable property of an object, a symbol is useful for describing:

var obj = {}; var descript = Symbol.  for (' This is an interesting object' =//' This is an interesting object '

String Template/template Strings

The template string is an enhanced version of the string, identified with an inverse quotation mark (') (note that it is not a single quotation mark). It can be used as a normal string, or it can be used to define multiple lines of string, or to embed variables and formulas in a string:

Console.log (' String text line 1//multi-line stringString Text line 2`);//string Text line 1//string Text line 2//embedding variables in stringsvarName = "Bob", time = "Today"; Console.log (' Hello ${name}, how is you ${time}?`);//Hello Bob, how is you today?//can be calculated in curly bracesvarParam_a = 1, Param_b = 2;varobj = {C:3};console.log (' The result is ${param_a+ Param_b + obj.c} ');//The result is 6

Template strings make it easy to combine strings with variables. Here is an example:

if (x > MAX) {    thrownew Error (' most ${max} allowed: ${x}!  `);     // the traditional notation is ' most ' +max+ ' allowed: ' +x+ '!'}

The template string can be immediately followed by a function name, and the function will be called to handle the template string:

 var  a = 5;  var  b = 10;  function     tag (s, v1, v2) {Console.log (s[ 0 1 + b} World ${a * b} ';  //  "Hello"  //  //   //  

Unlike regular functions, the Templat function receives a different parameter than the function tag above, which in turn accepts three parameters. The first argument is an array whose members are parts of the template string that do not have variable substitution, that is, variable substitution occurs only between the first member of the array and the second member, between the second member and the third member, and so on. The arguments after the first argument are the values that are replaced by each variable in the template string

In other words, the actual parameters of the tag function are as follows:

Tag ([' Hello ', ' World '], 15, 50)

Here is a more complex example of how to flatten each parameter back to its original location:

varTotal = 30;varmsg = PassThru ' The Total is ${total} (${total*1.05} withTax ) ';functionPassThru (literals) {varresult = ""; vari = 0;  while(I <literals.length) {result+ = literals[i++]; if(I <arguments.length) {result+=Arguments[i]; }  }  returnresult;} Msg//"The total is a (31.5 with tax)"
View Code

Another template string also has a String.raw () method, which is often used as a handler for the template string, returning the original format before the string is escaped:

Console.log (String.raw ' hi\n${2+3}!  `); // "hi\n5!" console.log (string.raw ' hi\u000a! `); // ' hi\u000a! '

Note: Most of the content in this article is referred to from the Nanyi teacher's ES6, but this example has been corrected in advance for all the code (including compatibility on Io.js, code error, and partial failure to mention feature methods).

In this context, we introduce all the ES6 features supported by Io.js.

Io.js Introduction (iii)--supported ES6 (bottom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.