36 字符串
36.1 字符串模板
let oDiv=document.querySelector("div");
let name;
let json={
div:{
className:"msg",
child:{
ul:{
className:"msg",
child:{
value:"hello",
className="msg"
}
}
},
ul:{
className="msg"
}
}
}
}
oDiv.innerHtml=`
<div class="${json.div.className}">
<ul class="${json.div.child.ul.className}">
<li class="${json.div.child.ul.child.li.className}">${json.div.child.ul.child.li.value}</li>
</ul>
</div>
`
let x=1,y=2;
`${x}+${y}=${x+y}`
对象.toString => [object Object]
只能写计算(变量本身;如果声明+赋值不可。嵌套也可以:
//test1
`${江西省`${九江}`}`
//test2
`${
`来自${江西省}`+`来自${九江}`
}`
反引号里可以加字符串,
涉及到花括号内部,必须字符串+变量
字符串里可以模板的嵌套
模板字符串:
变量传输会有空字符串↓:
tag`hello${a+b}world${a*b}`;
//等于
tag(["hello","world",""],15,50);
//当变量是第一个或是最后一个时,会在第一个前方或最后一个后方加入一个空字符串
arguments
是一个对应于传递给函数的参数的类数组对象。
function func1(a, b, c) {
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
console.log(arguments[2]);
// expected output: 3
}
func1(1, 2, 3);
36.2 字符串扩展方法
String.raw()让字符串不转义
String.raw`hi\nhello` //hi\nhello
includes() 返回布尔值,是否找到参数字符串
indexof 存在返回下标,不存在返回-1
startsWith() 返回布尔值,表示参数字符串是否在原字符串的头部
"211111sdafasfasfdew1".startWith("") //true
endWith() 返回布尔值,表示参数字符串是否在原字符串的尾部
验证后缀
"211111sdafasfasfdew1.jpg".endWith (".jpg") //true
repeat() 重复 返回新字符串,将原重复n次
"hello".repeat(2) //参数为次数
字符串会转化为数字,小数去小数
padStart(总长度,补全字符串 ) 头部补全 参数:总长度,补全字符串
补全后缀名和前缀
let url="www.bilibili.com";
let httpName="http://";
window.open(url.padStart(url.length+2,httpName));
padEnd(总长度,补全字符串 ) 尾部补全 参数:总长度,补全字符串
1.长度小于等于字符串长度,返回原字符串
2.大于但不完全超过,补全一半
3.省略第二个参数,默认用空格补全长度
'x'.padEnd(5) //'x '
trimStart 字符串消除头部空格
trimEnd 字符串消除尾部空格
中间用split或者正则
es6:ECMAscript 2015 2016 2017 2018 2019
36.3 数字格式的方法拓展
Number.isFinite() 用来检查一个数值是否优先
Number.isNaN() 检查一个值是否为NaN
↑都不进行数据类型转换
Number.isInteger() 用来判断一个数值是否为整数
浮点数和整数采用同样的存储方法。
参数不是数值,返回false
最大的数值:Math.pow(2,53) 2的53次方
Number.MAX_SAFE_INTEGER 上限
Number.MIN_SAFE_INTEGER 下限
Number.isSafeInteger() 用来判断一个数值是否在这个范围内
Math.trunc() 去除小数留整数 约等于Math.floor()
Math.floor(-0.32) //-1
Math.trunc(-0.32) //0
Math.sign() 用来判断一个数到底是正数,负数还是0。
x**y**z===x的y次幂的z次幂
Math方法
Math.max()
Math.min()
Math.ceil() 向上
Math.floor() 向下
Math.round() 标准,四舍五入
Math.random() 随机数
function random(min,max){
return Math.random()*(max-min)+min;
}