摘要:当使用时,基本字符串和字符串对象也会产生不同结果,会将基本字符串作为源代码处理,而字符串对象则被看作对象处理,返回对象。利用方法,我们可以将字符串对象转换为其对应的基本字符串。
笔试的时候总会遇到string 和 new String相关的问题,汇总一下
var s1 = "abc" var s2 = String("abc") var s3 = new String("abc") var s4 = new String("abc") console.log("s1 == s2", s1 == s2) //true console.log("s1 === s2", s1 === s2) // true console.log("s1 == s3", s1 == s3) //true console.log("s1 === s3", s1 === s3) //false console.log("s2 == s3", s2 == s3) //true console.log("s2 === s3", s2 === s3) //false console.log("s3 == s4", s3 == s4) //false console.log("s3 === s4", s3 === s4) //false
浏览器中运行截图如下:
上述字符串创建的三种形式,用“”创建是字符串字面量(通过单引号或者双引号定义)和直接调用String(不用new)生成的字符串都是基本字符串(可以理解为两种方式一样),使用new String创建的字符串为字符串对象。
基本字符串和字符串对象的区别
JavaScript会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象后才可以使用字符串对象的方法。当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候(基本字符串没有这些方法),JavaScript会自动将基本字符串转化为字符串对象并且调用相应的方法或执行查询。
当使用eval时,基本字符串和字符串对象也会产生不同结果,eval会将基本字符串作为源代码处理,而字符串对象则被看作对象处理,返回对象。
s1 = "2 + 2"; // creates a string primitive s2 = new String("2 + 2"); // creates a String object console.log(eval(s1)); // returns the number 4 console.log(eval(s2)); // returns the string "2 + 2"利用 valueOf 方法,我们可以将字符串对象转换为其对应的基本字符串。
console.log(eval(s2.valueOf())); // returns the number 4
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/85197.html
...例引用,因此intern()返回的引用和由StringBuilder创建的那个字符串实例是同一个。对str2比较返回false是因为“java”这个字符串在执StringBuilder.toString()之前已经出现过,字符串常量池中已经有它的引用了,不符合“首次出现”的原...
...。 原文:为什么阿里巴巴不建议在for循环中使用"+"进行字符串拼接 微信公众号:Hollis Fundebug经授权转载,版权归原作者所有。 字符串,是Java中最常用的一个数据类型了。关于字符串的知识,作者已经发表过几篇文章介绍过...
...tring;)V 12: astore_2 13: return } 我们主要看下面这段关于main方法的文本,里面涉及的指令不多,我整理了一下 ldc:将常亮加载到操作数栈astore_1: 将栈顶元素的值保存到变量1new: 为要创建的类实例开辟内存空间,并将地址压...
首先,我们先看下以下代码的输出情况 String s = "a" + "b"; System.out.println(s == "ab"); // true 将这段代码反编译后得到如下结果 public static void main(java.lang.String[]); Code: 0: aload_0 1: invokespecial #1 // Method java/la...
阅读 6245·2021-11-19 09:40
阅读 372·2021-10-27 14:19
阅读 563·2021-10-15 09:42
阅读 955·2021-09-14 18:02
阅读 447·2019-08-30 13:09
阅读 2712·2019-08-29 15:08
阅读 1811·2019-08-28 18:05
阅读 641·2019-08-26 10:25