(1)undefined:是所有没有赋值变量的默认值,自动赋值。
(2)null:主动释放一个变量引用的对象,表示一个变量不再指向任何对象地址。
2、何时使用null?
当使用完一个比较大的对象时,需要对其进行释放内存时,设置为 null。
3、null 与 undefined 的异同点是什么呢?
共同点 :都是原始类型,保存在栈中变量本地。
不同点:
(1)undefined——表示变量声明过但并未赋过值。
它是所有未赋值变量默认值,例如:
var a // a 自动被赋值为 undefined
(2)null——表示一个变量将来可能指向一个对象。
一般用于主动释放指向对象的引用,例如:
var emps = ['ss','nn']emps = null // 释放指向数组的引用
4、延伸——垃圾回收站
它是专门释放对象内存的一个程序。
(1)在底层,后台伴随当前程序同时运行;引擎会定时自动调用垃圾回收期;
(2)总有一个对象不再被任何变量引用时,才释放。
var str = "hello world"console.log(str.length)// 输出结果:11
var str = "apple"
var str1 = str.indexOf("p")
var str2 = str.indexOf("h")
var str3 = str.indexOf("pl")
var str4 = str.indexOf("pe")
console.log(str1)// 输出结果:1
console.log(str2)// 输出结果:-1
console.log(str3) // 输出结果:2
console.log(str4) // 输出结果:-1
注:多用来校测某一字符串中是否含有某一子串
var str = "helloworld"
var str1 = str.replace('world','apple')
console.log(str1)// 输出结果:helloapple
注:多与正则配合使用
eg.字符串去所有空格
var str = " hello world ! "
var str1 = str.replace(/\s/g, "")
console.log(str1)// 输出结果:helloworld!
eg.jQuery字符串去首尾两端所有空格方法
var str =" hello world "
console.log(str.trim())// 输出结果:hello world
1、substring("起始位置","结束位置[不写时,从起始位置截取到最后]");
2、substr("起始位置","截取长度 [不写时,从起始位置截取到最后]");
var str = "helloworld"
var str1 = str.substring(3,5)
var str2 = str.substring(3)
var str3 = str.substr(3,3)
var str4 = str.substr(3)
console.log(str1)// 输出结果:lo
console.log(str2)// 输出结果:loworld
console.log(str3)// 输出结果:low
console.log(str4)// 输出结果:loworld
注:substring截取,不包含结束位置
slice("起始位置","结束位置 [不写时,从起始位置截取到最后]");
var str = "helloworld"
var str1 = str.slice(1,3)
var str2 = str.slice(5)
console.log(str1)// 输出结果:el
console.log(str2)// 输出结果:world
注: 1、与substring截取类似,不包含结束位置;
2、 与substring截取不同,slice()结束位置为负时,代表反向位置(如:-1,代表字符串的倒数第一位);
var str = "helloWORLD"
var str1 = str.toLowerCase()
var str2 = str.toUpperCase()
console.log(str1)// 输出结果:helloworld
console.log(str2)// 输出结果:HELLOWORLD
var str = "hello"
var res1 = str.concat(" world ")
var res2 = str.concat(" world ","!")
console.log(res1)// 输出结果:hello world
console.log(res2)// 输出结果:hello world !
注:实际更常用简单的+(加号)
var str = "helloworld"
var str1 = str.charAt(5)
console.log(str1)// 输出结果:w
split("字符串或正则","分割长度[不写时,匹配后每个字符串都被分割]");
var str = "hello world hahaha"
var str1 = str.split(" ")
var str2 = str.split(" ",2)
var str2 = str.split(" ",3)
console.log(str1)// 输出结果:["hello", "world", "hahaha"]
console.log(str2)// 输出结果:["hello", "world"]
console.log(str3)// 输出结果:["hello", "world", "hahaha"]
var str = "hello world"
var str1 = str.match("hello")
var str2 = str.match("helo")
console.log(str1)// 输出结果:hello
console.log(str2)// 输出结果:null
注:与indexOF()、lastIndexOf()的不同之处,match()返回值为字符串,并常配合正则使用
var str = "hello world"
var str1 = str.search("hello")
var str2 = str.search("helo")
console.log(str1)// 输出结果:0
console.log(str2)// 输出结果:-1
注:与match()的不同之处,返回值为字符串中第一次出现所包含 子串或 第一个匹配正则的子串的起始位置