String的类型的数据

时间:2022-02-20 15:34:28

字符串类型的数据也是计算机基础。

var box = "lc";
var box1 = 'lc1'; //不管是单引号还双引号,都必须成对出现

1.ECMAscript规定字符串是不可改变。什么意思?

var box = 'lc';
box = box  + 'xiao'; //这不改变了box的值,而是重新创建了变量box

2.toString()(转换为字符串)

2.1语法示例:

var box = 11;
alert(typeof box.toString());

2.2toString()传参

Number类型转换String类型

var box = 10;
alert(box.toString());
alert(box.toString(2)); // '1010' 返回二进制,返回的数据类型已经字符串
alert(box.toString(8)); // '12' 返回八进制,返回的数据类型已经字符串
alert(box.toString(10));// '10' 返回十进制,返回的数据类型已经字符串
alert(box.toString(16)); // 'a' 返回十六进制,返回的数据类型已经字符串

3 String()(强制转换为字符串)

这个操作符主要是针对Null和Undefined。

示例1:

var box = null;
alert(String(box)); // 'null'
alert(typeof String(box)); // string

示例2:

var box;
alert(String(box)); // 'undefined'
alert(typeof String(box)); // string

说明:String()的方法比较智能,如果不是Null类型或Undefined类型数据,会自动用toString()