JavaScript字符串对象的创建和属性
字符串对象同样是JavaScript的内置对象,用来储存和处理文本。
1.字符串的创建
// 创建字符串
// 1.字面量的方式 "" '' ``
var str="hello";
var str1='world';
var str2=`hello China`;//模板字符串
// 2.使用 new 关键字创建 构造函数
var str3=new String("hello Nanjing");
console.log(typeof str);// String
console.log(str1);
console.log(str2);
console.log(typeof str3);// Object
两种声明方式的区别 :字面量方式声明,数据类型为string;使用new关键字创建,数据类型为object。
2.字符串的属性
// 字符串对象的属性
var str="hello China";
// length 字符串的长度
console.log(str.length);//11 空格字符也算长度
// constructor 对创建该对象的函数的引用 返回对象引用的原型
console.log(str.constructor);//ƒ String() { [native code] }
// prototype 向对象添加属性和方法
Array.prototype.func=function(){
for(var i=0;i<this.length;i++){
console.log(this[i])
}
}
var arr=[1,2,3,4,5,6,7];
arr.func();
String.prototype.func=function(){
console.log(this.length);
}
str.func();
视频讲解链接:
https://www.bilibili.com/video/BV1HZ4y1W792/