048_String对象

1. String对象

1.1. String是对原始字符串的包装对象。

1.2. 创建String对象的语法:

var myStr = new String(s);

1.3. 参数s是要存储在String对象中的字符串。

1.4. 当String()和运算符new一起作为构造函数使用时, 它返回一个新创建的String对象, 存放的是s的字符串表示。

2. String对象属性

3. String对象方法

4. 使用字面量创建字符串和String对象创建字符串

4.1. 使用字符串字面量创建字符串和String对象创建字符串

var str1 = new String('hello china'); // 使用String对象创建字符串
var str2 = 'hello china'; // 使用字符串字面量创建字符串

4.2. 使用字面量创建字符串和String对象创建字符串的不同

4.2.1. 使用字面量创建的字符串是原始值, 储存在栈中。

4.2.2. 使用String对象创建的字符串是对象(引用类型), 储存在堆中。

4.2.3. 字符串字面量和String对象创建字符串的内存结构:

4.2.4. 使用对象创建字符串比使用字符串字面量创建字符串复杂的多(就是因为String对象多执行了一个String()构造函数), 执行效率低, 因此我们通常使用字符串字面量创建字符串。

4.2.5. 使用==运算符判断使用字面量和String对象创建的相同值的字符串是否相等时, 结果是true, 因为字符串内容相同。

4.2.6. 使用===运算符判断使用字面量和String对象创建的相同值的字符串是否相等时, 结果是false, 因为字符串虽然内容相同, 但类型不同, 一个是字符串, 一个是对象。

5. 字符串原始值可以使用String对象的属性和方法

5.1. 字符串原始值, 比如"hello china", 无法拥有属性和方法, 因为它们不是对象。

5.2. 但是通过JavaScript, String对象的属性和方法也可用于原始字符串, 因为在执行属性和方法时JavaScript将原始字符串视为伪对象。

5.3. 需要注意的是, JavaScript的字符串是不可变的(immutable), String类定义的方法都不能改变字符串的内容。像toUpperCase()这样的方法, 返回的是全新的字符串, 而不是修改原始字符串。

6. String对象重写了Object对象的constructor: ƒ String()属性, 和toString()、valueOf()这两个方法。

7. toString()方法

7.1. toString()方法返回字符串。

7.2. 语法

stringObject.toString()

8. valueOf()方法

8.1. valueOf()方法可返回String对象的原始值。

8.2. 语法

stringObject.valueOf()

8.3. String对象的toString()方法和valueOf()方法是一样的。

9. 例子

9.1. 代码

<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="utf-8" />
		<title>String对象</title>
	</head>
	<body>
		<script type="text/javascript">
			var str1 = new String('hello china');
			var str2 = 'hello china';

			document.write('str1 = ' + str1 + '<br />');
			document.write('str2 = ' + str2 + '<br />');
			document.write('(str1 == str2) = ' + (str1 == str2) + '<br />');
			document.write('(str1 === str2) = ' + (str1 === str2) + '<br />');
			document.write('(str1.valueOf() === str2) = ' + (str1.valueOf() === str2) + '<br />');
			document.write('(typeof str1) = ' + (typeof str1) + ', (typeof str1.valueOf()) = ' + (typeof str1.valueOf()) + '<br />');
			document.write('(typeof str2) = ' + (typeof str2) + ', (typeof str2.valueOf()) = ' + (typeof str2.valueOf()) + '<br />');
			document.write('(str1.toString() === str2) = ' + (str1.toString() === str2) + '<br />');
			document.write('(typeof str1) = ' + (typeof str1) + ', (typeof str1.toString()) = ' + (typeof str1.toString()) + '<br />');
			document.write('(typeof str2) = ' + (typeof str2) + ', (typeof str2.toString()) = ' + (typeof str2.toString()) + '<br />');
		</script>
	</body>
</html>

9.2. 效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值