Home > Web Front-end > JS Tutorial > Less popular knowledge points about JavaScript

Less popular knowledge points about JavaScript

巴扎黑
Release: 2017-07-22 15:24:59
Original
1241 people have browsed it

Native functions

Commonly used native functions

String()

Number()

Boolean()

Array()

Object()

Function()

RegExp()

Date()

  Error()

  Symbol()

  Internal properties [Class]

   Alltypeof Objects with a return value of object contain an internal attribute [Class], This attribute cannot be directly Access is generally viewed through Object.prototype.toString(..) .

                             Object.prototype.toString.call([1,2,3]);   ##     // "[ object Array]"

Basic type value

Object.prototype.toString.call(null); // "[object Null]"

   

Encapsulated object packaging

                   Since the basic type value does not have .length

and

.toString() Such properties and methods.                                 With

new

keyword

)

var a = "abc"; var b = new String (a);   var c = Object(a);     It is generally not recommended to use the encapsulated function directly

  Unpacking

    To encapsulate the basic type value in the object, you can use the

valueOf() function.

    var a = new String("abc");    var b = new Number(42);

    var c = new Boolean(true); a.valueOf(); // "abc"

b.valueOf(); // 42

c.valueOf(); // true

   Native function as constructor

   Array(..)

   var a = new Array(1,2,3);

    a; // [1,2,3]

    var b = [1,2,3]    b; // [1,2,3]

Constructor

Array(..),

is not required to have the keyword

new,

will be automatically filled in if not When the

Array

constructor takes only one parameter, the parameter will be the preset length of the array

instead of being an element in the array.    var a = new Array(3); Do not create and use empty cell arrays  Object(..), Function(..), and RegExp(..)

    Do not use

Object(..) / Function(..)/RegExp(..)

unless absolutely necessary. Date(..)

andError(..)

The creation time must use new Date(), is mainly used to obtain the current Unix timestampDate .new()Then get it through getTime() in the date object.

  Creating an error object(error objec) Mainly to obtain the current running context.

Symbol(..)

Basic data type —— symbol. Symbols have unique special values, and using them to name attributes will not easily lead to duplicate names.

The static attribute form of Symbol , Symbol.create, Symbol.iterator

obj[Sybol.iterator] = function() {/*..*/}

Use Symbol(..) native constructor to customize symbols, cannot bring new Keyword, otherwise an error will be reported.

    var mysym = Symbol("my own symbol");

   mysym; // Symbol(my own symbol)

    mysym.toString(); / / "Symbol(my own symbol)"

     typeof mysym; // "symbol"

    var a = {};

      a[mysym ] = "foobar";

Object.getOwnPropertySymbols(a);

// [Symbol(my own symbol)]

Prototype type

The native constructor has its own .prototype object such as: Array.prototype,

String.prototype.

    String#indexOf(..)

     Find the position of the specified string in the string.

    String#charAt(..)

                                        will will will need should the character

#substring(..) and String# slice(..)

Get the specified part of the string

String#toUpperCase() and String#toLowerCase()

Convert the string to uppercase and lowercase

String #trim()

Remove the spaces before and after the string and return the new string

Forced type conversion

                                           ‖                                 wanted should you should be sure] This is the case shown,

Implicit cases are usually casts.

     Type conversion in JavaScript always returns a scalar basic type.

Abstract value operation

Forced type conversion to string Default

toString()

method of array has been redefined to stringify all units

and then connect them together.      var a = [1,2,3];   a.toString(); // "1,2,3"   JSONString replacement,

    JSON.stringify(..) Will automatically occur when undefined, function and symbol are encountered in the object Ignore it, and null will be returned in the array.

For example:

JSON.stringify(undefined); // undefined

JSON.stringify(function(){}); // undefined

       JSON.stringify(

        [1,undefined,function(){},4]

      ); // "[1,null,null, 4]"

      JSON.stringify(

    {a:2,b:function(){}}

   ); // "{"a":2} "

    toJSON() The return should be an appropriate value, which can be of any type, and then JSON.stringify(. .) Align for stringification.

    ToNumber

     Sometimes it is necessary to use non-numeric values ​​as numbers, such as mathematical operations.

      true is converted to 1, false is converted to 0, undefined is converted to NaN

null is converted to 0

    In order to convert the value to the corresponding basic type, the abstract operation ToPrimitive,first checks whether the value has the valueOf() method, and if so, use it The value is cast. If not, use the return value of toString()

to perform forced type conversion. If neither valueOf() nor toString() returns a value , a TypeError error will occur.

  ToBoolean

    false value:

     Values ​​can be divided into the following two categories.

      1.can be cast to the value of false

      2.Others ( is lightweight type converted to the value of true)

The following are false values ​​

undefined

null

false

+0,-0 and NaN

""

     False value object: The browser, in some specific circumstances, based on the regular JavaScript syntaxCreated some foreign values, these are "False Value Object"

                               #False Value Object

The true value is the value outside the false value list

Explicit cast type conversion

###

Display conversion between strings and numbers

Display forced type conversion between strings and numbers is through String(..) andNumber(..).

Explicit cast conversion between the two

var a = 42;

var b = String(a);

var c = "3.14";

var d = Number(c);

b; // "42"

d: // 3.14

    There are other ways to achieve display conversion between strings and numbers

var a = 42 ;

var b = a.toString();

var c = "3.14";

var d = +c;

b; / / "42"

d: // 3.14

Convert date display to numbers

Unary operator+ ## Another common use of # is to coerce a date object (Date) object into a number.

var timestamp = +new Date();

Explicitly parse numeric string

Numbers and the return result of casting a string to a number are both numbers.

For example:

var a = "42";

var b = "42px";

Number (a); // 42

parseInt(a); // 42

Number(b); // NaN

parseInt(b); // 42

The parsing allows the string to contain non-numeric characters. The parsing is in order from left to right. If encounters a non-numeric character, it will stop.

    parseInt(..)

is for strings, like parseInt(..) There is no need to pass numbers and other types of parameters Use

to display the conversion to a Boolean value

ToBoolean

is explicit ToBoolean mandatory Type conversion:

var a = "0";

var b = [];

var c = {};

var d = "";

var e = 0;

var f = null;

var g;

Boolean(a); // true

Boolean(b); // true

Boolean(c); // true

Boolea(d); // false

Boolea(e); // false

Boolea(f); // false

Boolea(g); / / false

  Unary operator! Explicitly cast the value to a Boolean value.

var a = "0";

var b = [];

var c = {};

var d = "";

var e = 0;

var f = null;

var g;

!!a; // true

!!b; // true

!!c; // true

!!d; // false

!!e; // false

!!f; // false

!!g; // false

Implicit cast

Implicit simplification

Implicit cast conversion between strings and numbers

The + operator can be used for both number addition and string concatenation.

var a = "42";

var b = "0";

var c= 42;

var d = 0 ;

a + b; // "42"

c + d; // 42

      of the object - The operation is similar to + ;

var a = [3];

var b = [1];

a - b ; // 2

Implicit cast to boolean

Implicit cast to boolean Value

The following situations will cause implicit cast conversion

1.if(..) The conditional expression in the statement.

2.for(..;...;..)Conditional judgment expression in the statement(The second )

3.while(..) anddo..while(..) Conditions in the loop Judgment expression.

4.? : Conditional expression in

5.Logical operator|| (Logical or ) and (logical AND) The operand on the left (as a conditional expression)

   || &&

|| It must be of Boolean type, but the value of one of the two operandsvar a = 42;var b = "abc";

var c = null;

a || b; // 42

a && b; // "abc"

c || b; // "abc"

c&& b; // null

If for

||

If the conditional judgment result is

true , the value of the first number will be returned. If is false , the second operand will be returned. && is the opposite.

The following is a || very common

|| usage. function foo(a,b){a = a || "hello";

b = b || "world";

console.log(a + " " + b );

}

foo(); // "hello world"

foo("yeah","yeah"); // "yeah yeah"

Forced type conversion of symbols

Relaxed equality and strict equality

     "== allows casts in equality comparisons, while === does not allow "

Abstract equality

There are a few unconventional ones that need to be noted

NaN is not equal to NaN

+0 Equal to-0

Loosely unequal != is The opposite of ==, !== Same as

Characters Equality comparison between strings and numbers

1.If Type(x) is a number, Type( y) is a string, then the result of x== ToNumber(y)

is returned.

2.If Type(x) is a string, Type(y) ## If # is a number, the result of ToNumber(x)== y is returned.

Equality comparison between other types and Boolean types

==

The most error-prone place istrue andfalse Equality comparison with other types

var a = "42";

var b = true;

a == b; // false

1.

If Type(x) is a Boolean type, Then return the result of ToNumber(x) == y

2.

ifType(y) is a Boolean type, then the result of x == ToNumber(y)

is returned. First:

var x = true;

var y = "42";

x == y; // false

Inversely

var x = "42";

var y = false;

x == y; // false

null

and# Equality comparison between ##undefined The

between null

and undefinded == also involves hermit cast. 1.

If

x is null, y is undefined , then the result is true

2.If x is undefined, y is null, The result istrue

var a == null;

var b;

a == b; // true

a == null; // true

b == null; // true

a == false; // false

b == false; // false

a == "" ; // false

b == ""; // false

a == 0; // false

b == 0; // false

  Equality comparison between objects and non-objects

About objects and (Object/Function/ Array) and scalar primitive types (String/Number/Boolean Comparison between values ​​).

1.If Type(x) is a string or number, type(y) is an object, returns the result of x == ToPrimitive(y)

2.If Type(x) is an object, Type(y) is a string or number, then

is returned. ToPromitive(x) == y results.

var a = 42;

var b = [42];

a == b; // true

var a = "abc";

var b = Object(a); // new String(a) Same

a === b; // false

a == b; // true

a == b The result is true, should be b Perform forced type conversion through ToPromitive , and return the basic type value "abc" , equal to a .

Comparison of false values ​​for equality

The following is a regular and unconventional comparison

"0" = = null; // false

"0" == undefined; // false

"0" == false; // true -- Halo!

"0" == NaN; // false

"0" == 0; // true

"0" == ""; / / false

false == null; // false

false == undefined; // false

false == NaN; // false

false == 0; // true -- Halo!

false == "" // true -- Halo!

false == [] // true -- Halo!

false == {} // false

"" == null; // false

"" == undefined; // false

"" == NaN; // false

"" == 0; // true -- Halo!

"" == []; // true -- Halo!

"" == {}; // false

0 == null; // false

0 == undefined; // false

0 == NaN; // false

0 == []; true -- Dizzy!

0 == {}; false

Because they are false positives.

            Extreme cases

           [] == ![] // true

              Forced type conversion of Boolean value [] == ![] becomes [] == false,

     2 == [2]

    "" = = [null]; //true

42 == "43" // false

"foo" == 42; // false

"true" = '"" // false

42 == "42" // true

"foo" == ["foo"] // true

Safely use implicit casts

1.If the values ​​on both sides have true Or false, Do not use ==.

2.If there is ## on both sides #[],"" or 0 , try not to use ==. At this time it is best to use === to avoid forced type conversion.

Abstract relationship comparison

Both sides are string comparison

var a = ["42"];

var b = ["043"];

a < b; // false

a

and b are not accurately converted to numbers because ToPrimitive returns a string,

Compares the two strings "42 " and "043" , because "0" is alphabetically smaller than

"4"

, so the final result is false.

## Similarly

var a = [4,2];

var b = [0,4,3];

a < b; // false

a is converted to "4,2" , b is converted to " 0,4,3” The same style is compared in alphabetical order.

var a = {b: 42};

var b = {b:43};

a < b ; // false

a is [object Object], b is also [object Object] So in alphabetical order

a < b is not established.

The following example

var a = {b: 42};

var b = {b:43};

a < b; // false

a == b; // false

a > b; // false

a <= b; // true

a >= b; // true

The above is the detailed content of Less popular knowledge points about JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template