字符串方法:
用单引号、双引号、反引号引起来的就是字符串,
-
字符串长度:
定义一个变量接收一个字符串 可以调用字符串的length属性(转换为包装类型)
Var str = ‘abc’ //基础类型值不可更改
New String(str) (new String(str)).length //转换为包装类型对象 再用length属性
注意:字符串str.length 无法更改 为只读属性
Str.length = 100
Console.log(str.length) //3 -
转化为字符串(String 和 toString):
null 和 undefined 没有 toString() 方法 //用法:str.toString()
String() 方法可以将任意类型转化为字符串 //用法同上
3.ES6字符串:
在ES6中字符串就是反引号引起来的格式,并且用反引号引起来的跨行字符串不会报错,而在编辑器中单引号和双引号不支持换行 模板语法如下:
Var a = ‘xx’
Var age = 15
Document.write(`${a},${age}`) -
indexOf()方法:
在指定字符串中寻找要找的字符的索引位置 并返回这个值第一次出现的位置的索引。
Var str = ‘dajsj’
str.indexof(‘j’) //2
str.indexof(‘j’,3) //支持传递两个参数 第二个参数对应开始查找的起始位置
注意:若在字符串中能够找到该字符,则返回该字符对应的索引位置,若找不到该字符,则返回-1 -
字符串截取方法:
var str = ‘hello world!’;console.log(str.substr(0,3));//hel
index1,index2,其中index1指的是索引的起始位置,index2指的是截取的长度console.log(str.substring(0,3));
//hel //截取字符串方法,当startindex > endindex 时,会自动交换位置再截取,只有一个参数startindex时则截取从startindex以后的所有字符串 不支持反向索引console.log(str.slice(-3,-1));
//截取字符串方法 当startindex > endindex 时,不会自动交换位置,只有一个参数startindex时则截取从startindex以后的所有字符串 支持反向索引,但startindex < endindexconsole.log(str.charAt(2)) //截取index对应的字符
-
其他方法:
var str = 'a ijh ';
console.log(str.trim()) //去掉字符串中前后的空格
console.log(str.charCodeAt(0)) //取到index对应字符对应的ASCll编码
js执行步骤:
- 代码检查
- 变量提升(用var声明的变量存在变量提升)
- 函数提升
- 执行语句
Object:
定义变量的方式:
Var obj = {
Name:”alex”,
Age:18
sayHello:function(){
return this.Name
}
}
Var obj1 = new Object
Obj1.name = “wusi”
Obj1.age = 20
访问对象属性方法的方式:对象.属性名,对象.方法 对象[‘属性名’] 对象‘函数名’
Obj.Name obj.sayHello() obj[“Name”] obj“sayHello”
包装对象:
数字 字符串 布尔值
var num = new Number
var str = new String
var bol = new Boolean
new 操作符操作产生一个对象 ,可以有属性和方法
var Str=new Boolean;
console.log( Str );
Str.name=“alex”;
console.log( Str.name )
var str = ‘dhfdala
var str1=new String(str);
console.log(str1)
console.log(typeof str1);//object
str1.length=100;
console.log(str1.length); //7
str1.test=“abcd”;
console.log(str1.test); //’abcd’
console.log(str1.substring)
str1.substring=100;
console.log(str1.substring) //100
例:
var test0809=false;
console.log( test0809.toString() ); //“false”
console.log(typeof test0809) //“Boolean”
console.log(typeof test0809.toString()) //“string”
console.log( tes0t809.toString ) //function(){ [native code] }
console.log(typeof test0809.toString) //“function”
test809.toString=100;//临时包装对象
console.log(test809.toString) //function(){ [native code] }
var test8090=new Boolean; //{false}
test8090.toString=100; //修改属性值
console.log( test8090.toString ) //100
// console.log( test8090.toString() ); //报错
变量作用域:
Var a = 100
function myfn(){
var a = ‘abc’
a = 1000
}
Console.log(a) //100
myfn()
console.log(a) //100
//函数体内可以访问全局变量(函数体内可以访问函数体外的变量,函数体外不能访问函数体内用var 声明的变量)
//函数体内的局部变量与全局变量同名时优先访问局部变量
在运行环境最外侧,不管用没用var声明 都是全局变量
在函数内部,用var声明的变量是局部变量,没有用var声明的变量是全局变量
函数访问变量是从内到外,逐层查找,
注意:函数定义表达式必须是用function开头才有函数提升
Var fn = function(){} //此时不存在函数提升,只有变量提升