js中定义字符串的三种⽅法
今天遇到⼀道⾯试题,如下:
function showCase(value) {
switch (value) {
case 'A':
console.log("A");
break;
case 'B':
console.log("B");
break;
case undefined:
console.log("undefined");
break;
default:
console.log("do not konw")
}
}
    showCase(new String('A')) // do not konw
console.log(new String('A') === 'A') //false
showCase('A') //A
console.log(new String('A') == 'A') //true
涉及知识点有两个:
(1)js中定义字符串的三种⽅法区别
  三种⽅法如下:
var str = 'ABC';
var str1 = String('ABC');
var str2 = new String('ABC');
  经过⽐较测试发现:
console.log(str == str1) //true
console.log(str == str2) //true
console.log(str1 == str2) //true
console.log(str === str1) //truejs原型和原型链的理解
console.log(str === str2) //false
console.log(str1 === str2) //false
//typeof 判断对象是什么类型的实例,返回值为说明运算数类型的字符串。
//返回值结果:“number”、“string”、“boolean”、“object”、“function”、“undefined”
console.log(typeof str) //string
console.log(typeof str1) // string
console.log(typeof str2) //object
//instanceof 判断对象的类型,通过判断对象的原型链中能否到类型的 prototype
//只能⽤来判断两个对象是否属于实例关系,⽽不能判断⼀个对象实例具体属于哪种类型
console.log(str instanceof String) //false
console.log(str1 instanceof String) //false
console.log(str2 instanceof String) //true
三者的区别在于使⽤new定义的字符串其类型是object对象。
我们都知道js中类型分为基本类型:Boolean、Number、String、Null、Undefined、symbol(es6)和引⽤类型:Object。
基本类型是存储在栈(stack)内存中的,数据⼤⼩确定,内存空间⼤⼩可以分配。
引⽤类型是存储在堆(heap)内存中的,并在栈中存储指向堆的地址。
因此前两种⽅式定义的是存储在栈中且值相等,⽽第三种⽅法定义的只是栈中的指针。
  扩展知识:原始类型与包装对象
    在js中number、string、boolean三者属于原始类型,它们都存在⽀持构造函数且可⽤于初始化原始值的包装对象new Number()、new String()、new Boolean()。
    我们会看到这种代码:
console.log(str.length) // 3
str.say = 'hello'
console.log(str.say) //undefined
    为什么可以像对象⼀般直接访问原始类型str的length属性呢?
      这是因为当⽤到某个原始值的⽅法或属性时,后台会⾃动创建相应的原始包装类型的对象,从⽽暴露出操作原始值的各种⽅法,当⽤完时销毁。
    ⽽为什么不能为其添加⽅法或属性呢?
      因为包装对象的⽣命周期只存在于访问它的那⾏代码执⾏期间,上⽅代码第⼀⾏调⽤length对象会创建⼀次包装对象,第⼆⾏也会创建⼀次包装对象并为其赋予say属性,第三⾏也会创建⼀次包装对象,这三⾏的对象是不同的,且在当⾏执⾏完后就被销毁,因此不能在运⾏期间给原始值添加属性或⽅法。相⽐于此,使⽤new关键字实例化引⽤类型的⽣命周期会在离开作⽤域时被销毁。
    综上:包装对象也是对象,从⽽得到打印三种类型分别为:string(原始类型) , string(原始类型) , object(包装对象).
(2)switch case的判断是全等(===)判断。
    全等要满⾜:1、引⽤类型:指向同⼀个对象(同⼀个地址)。
          2、基本类型:类型必须相同,值必须相等。