Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String() 与 new String() 的差异 #14

Open
TieMuZhen opened this issue Nov 16, 2021 · 0 comments
Open

String() 与 new String() 的差异 #14

TieMuZhen opened this issue Nov 16, 2021 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

面试题目

function showCase(value) {
    switch(value) {
    case 'A':
        console.log('Case A');
        break;
    case undefined:
        console.log('undefined');
        break;
    default:
        console.log('Do not know!');
    }
}
showCase(new String('A'));

这里先不讲答案,答案在最后。

JavaScript 中的字符串创建

在 JavaScript 中大致有3种创建字符串的方式,下面我们来看看它们的区别:

<script type="text/javascript">
var str1 = "hello zwkkk1!";
var str2 = String('hello zwkkk1!');
var str3 = new String('hello zwkkk1!');
//第一部分
console.log(typeof str1);   //string
console.log(typeof str2);   //string
console.log(typeof str3);   //object
//第二部分
console.log(str1 == str2);  //true
console.log(str1 == str3);  //true
console.log(str2 == str3);  //true
//第三部分
console.log(str1 === str2); //true
console.log(str1 === str3); //false
console.log(str2 === str3); //false
</script>

  从上面代码的第一部分我们可以知道双引号""创建的字符串和调用String()返回的都是string类型,而将String()new作为构造函数返回的是Object类型。
  从第二、第三部分我们可以知道基本字符串值与对象包装的字符串类型==时可以返回true,用===判定返回false
  switch 语句在比较值时使用的是全等操作符===,不会发生类型转换。

答案

'Do not know!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant