字符串的常用方法
charArt(索引)
- 是找到字符串中指定索引位置的内容返回
代码如下:
var str ='Jack' // J a c k 字符串
// 0 1 2 3 索引号
var res = str.charAt(2) //括号里面是索引号
console.log(res) //输出结果 c
- 如果没有对应的索引,那么就会返回空字符串
var str = 'Jack'
var res = str.charAt(10)
console.log(res) //输出结果''
charCodeAt
- charCodeAt索引就是返回对于索引位置的Unicode编码
var str = 'Jack'
var res = str.charCodeAt(0)
console.log(res) //输出结果 74
- 因为J在Unicode对照表里面存储的是74,所以就会返回74
toLowerCase 和 toUpperCase
- 这里两个方法分别使用用来字符串转成小写字母和大写字母
var str = hello
var res = str.toUpperCase() //转成大写字母
console.log(res) //输出结果 HELLO
var str = HELLO
var res = str.toLowerCase() //转成小写字母
console.log(res) //输出结果 hello
substr、substring、slice三个区别
这三个都是用来截取字符串的
substring:从哪个索引开始,到哪个索引截止(包含开始索引,不包含结束索引)
var str = 'hello'
// 01234
var res = str.substring(1,3)
console.log(res) //输出结果 el
//从索引1开始,到索引3截止,包含前面的索引不包含后面的索引
substr:从哪个索引开始,截取多少个
var str = 'hello'
// 01234
var res = str.substr(1,3)
console.log(res) //输出 ell
//从索引1开始,截取3个,所以得到的是ell
slice:默认是从左到右
var str = 'js is so good'
var res = str.slice(-1,-3) //-1,-3 是从右往左 所以冲突不截取内容
console.log(res) //输出结果 无
concat(新字符拼接原字符后面)
var str = 'hello'
var res = str.concat('wo') //新字符
console.log(res) //输出结果 hellowo
IastIndexOf(查找字符串索引)
var str = 'hello'
var res = str.lastIndexOf('o')
console.log(res) //输出结果 4
includes(查找字符串)
var str = 'hello'
var res = str.includes('lo') //查找字符串内容
console.log(res) //输出结果 true
- 需注意查找字符串 如果有就返回 true,没有就返回 false
trim(去除字符串左右两边的空格)
var str = ' hello ' //字符串左右都有空格
var res = str.trim()
console.log(res) //输出结果hello,字符串两边的空格都去掉了
trimEnd()
replace(替换字符串,并且只能替换一个)
var str = 'hello name'
var res = str.replace('name','hello')
console.log(res) //输出 hello hello
Math和Date
- Math 是 js 的一个内置对象,提供了一堆的方法帮助我们操作 数字
- Date 是 js 的一个内置对象,提供了一堆的方法帮助我们操作 时间
Math
- 没有什么多余的东西,就是一堆的方法来操作数字
random
-
Math.random()
这个方法是用来生成一个0 ~ 1
之间的随机数 -
每次执行生成的数字都不一样,但是一定是
0 ~ 1
之间的 -
生成的数字包含 0 ,但是不包含 1
var num = Math.random() console.log(num) // 得到一个随机数
round
-
Math.round()
是将一个小数 四舍五入 变成一个整数var num = 10.1 console.log(Math.round(num)) // 10 var num2 = 10.6 console.log(Math.round(num2)) // 11
abs
-
Math.abs()
是返回一个数字的 绝对值var num = -10 console.log(math.abs(num)) // 10
ceil
-
Math.ceil()
是将一个小数 向上取整 得到的整数var num = 10.1 console.log(Math.ceil(num)) // 11 var num2 = 10.9 console.log(Math.ceil(num2)) // 11
floor
-
Math.floor()
是将一个小数 向下取整 的到的整数var num = 10.1 console.log(Math.floor(num)) // 10 var num2 = 10.9 console.log(Math.floor(num2)) // 10
max
-
Math.max()
得到的是你传入的几个数字之中 最大 的那个数字console.log(Math.max(1, 2, 3, 4, 5)) // 5
min
-
Math.min()
得到的是你传入的几个数字之中 最小 的那个数字console.log(Math.min(1, 2, 3, 4, 5)) // 1
PI
-
Math.PI
得到的是π
的值,也就是3.1415936...
console.log(Math.PI) // 3.141592653589793
- 因为计算机的计算精度问题,只能得到小数点后 15 位
- 使用 Math.PI 的时候,是不需要加 () 的