字符串扩展
for(var i=O;i<5;i++){
// console.log('第'+i+'个');
console.log(`第${i}个`);
查找元素
var str="hello world'
indexOf
console.log(str.indexOf('hello'));
//返回子串的下标的下标找不到返回-1
includes
console.log(str.includes('world'));
//查找子串找到返回true否则false
startswith
console.log(str.startswith('world',6));
//子串是否是当前字符串的开头 true false
endsswith
console.log(str.endsswith('world'));
//子串是否是当前字符串的结束 true false
repeat()
var str='he'
console.log(str.repeat(20)); //重复hehehehehehehehehehehehehehehehehehehehe
padStart()
padStart()
和padEnd()
一共接受两个参数,第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串。
var s= 'a'
console.log(s.padStart(5,'sb')); //sbsba
padEnd()
var s= 'a'
console.log(s.padEnd(5,'sb')); //asbsb
trim()
trimStart/trimLeft trimEnd/trimRight ES2019 删除空格
var str=' hello '
console.log(str.length);
console.log(str.trim(),str.trim().length));//去掉空格
console.log(str.trimStart(),str.trimStart().length);//去掉开始空格
// 7
hello 5
hello 6
交换变量
let a=5,b=6
console.log([a,b]=[b,a])
//6,5
function show(){
return {a:1,b:2,c:3}
}
let {a,b,c}=show()
console.log(a,b,c)
//1 2 3
扩展运算符 ...spread
console.log(...[1,2,3])
//1 2 3
console.log([...document.querySelectorAll('*')]) //返回所有标签
//[html, head, meta, meta, title, body, ul, li, li, li, li, script]
复制数组
let arr=[1,2,[3,4]]
let arr2=[...arr]
console.log(arr2) //[1, 2, Array(2)]
console.log(arr2==arr) //false
console.log(arr2[2]==arr[2]) //true
let arr=[1,2,3,4]
let arr2=[...arr]
console.log(arr2)
// [1, 2, 3, 4]
function show(a,b,c,d){
log(a,b,c,d)
}
var arr=[1,2]
show(0,...arr,3,4)
//0 1 2 3
合并数组
let arr=[1,2],arr2=[3,4]
console.log(arr.concat(arr2)) //ES5
console.log([...arr,...arr2] //ES6
//[1, 2, 3, 4]
剩余参数...rest
let arr=[1,2,3]
let [a,...rest]=arr //rest只能放后面 返回NodeList 对象
console.log(a,rest)
//1 [2, 3]