The difference between a string () and a new string () in JS

Source: Internet
Author: User

See this question today, as follows:

var yiifaa = ‘yiifaa‘,    str1 = new String(yiifaa),    str2 = String(yiifaa)
    • 1
    • 2
    • 3

3 variables are declared and assigned, then the questions are as follows:

//  请确认以下的判断是否准确str1 === yiifaa//str2 === yiifaa//typeof str1 === typeof str2
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

According to the syntax of JS, to meet the conditions of = = = as follows:
1. If it is a reference type, then two variables must point to the same object (the same address);
2. If it is a base type, the values must be equal, except that the type must be the same for the two variables.

Then switch the topic to the string object, there are three ways to declare the string (see the first code), but the resulting type is different, the result is as follows:

//  类型为string,为基本类型typeof yiifaa//  类型为object,为引用类型typeof str1// 类型为string,为基本类型typeof str2
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

Now the answer is clear, as follows:

//  false, 因为str1为引用类型str1 === yiifaa//  true, 因为都是基本类型,并且值相等str2 === yiifaa// false, 虽然都是字符串,但分别为object与stringtypeof str1 === typeof str2
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
Summarize

Very magical string object, on the one hand can be as the basic type, on the other hand can also be used as reference type, more amazing is, for String.prototype Add method, basic type can also refer to, how to do?

The difference between a string () and a new string () in JS

Related Article

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.