字符串模板:
在没有学ES6之前我们在项目中遇到字符串都是采用拼接的方式,如下:
var str='<p class="musicName">'+info.song+'</p>\
<p class="singer">'+info.singer+'</p>'
那么ES6的写法如下:
var str=`<p class="musicName">${info.song}</p>
<p class="singer">${info.singer}</p>`
用`号包裹整个字符串。(ESC下面的按键)
${info.song} 代替了 '+info.song+'
换行符\也不用输入了。整个代码看着一幕了然。
接下来说一下关于字符串的方法:
1 字符串查找:
str.indexOf(要找的内容) 返回索引位置,如果没找到返回-1 例:
let str='hello world';
console.log(str.indexOf('hello')); // 0 从索引为0的地方发现了要找的hello
console.log(str.indexOf('green')); // -1 没有找到
str.includes(要找的内容) 返回值 true/false 例:
let str='hello world';
console.log(str.includes('hello')); // true
console.log(str.includes('green')); // false
注意只要是被找的内容在str里面就会返回true,如果str里面写的是hello123 world 那么也是返回true,这是一个包含的关系。
2 字符串以什么开头:
str.startWith(检测内容)
3 字符串以什么结尾:
str.endsWith(检测内容) 例子如下:
let str='https:// .png';
console.log(str.startsWith('https')); // true
console.log(str.endsWith('.png')); // true
4 重复字符串:
str.repeat(次数)
let str='https:// .png';
console.log(str.repeat(4)); // 输出了4次 https:// .pnghttps:// .pnghttps:// .pnghttps:// .png
函数变化:
1.函数可以设置默认参数。
function test(a=0,b=5){
console.log(a); // 0
console.log(b); // 5
}
test();
function test1({x=2,y=3}){
console.log(x); // 2
console.log(y); // 3
}
test1({}); //相当于 test1({x=2,y=3}={}) 和之前解构赋值比较像,左右对等的原则
2.函数参数默认已经定义了,不能再使用let ,const声明
function test(a=5){
let a=3;
}
test(); //报错
扩展运算符...,Rest运算符:
1.展开数组:在数组前面加上...符号,数组被展开了。
console.log(...[1,2,3,4,5]) // 1 2 3 4 5
2.用在函数传参上,加上...后可以把数组当成参数使用
let arg=[2,3,4,5];
function test(a,b,c,d){
console.log(a,b,c,d); // 2 3 4 5
}
test(...arg);
3.用在字符串上。
let str="hello"
console.log(...str); //h e l l o
4.变成数组。
function test(...a){
console.log(a); // [1, 2, 3, 4, 5]
}
test(1,2,3,4,5)
5.伪数组转数组
<script>
window.οnlοad=function(){
var liarr=document.querySelectorAll('ul li');
console.log(liarr); // 伪数组
var arr=[...liarr]; // 用...转化之后
console.log(arr); // 数组
}
</script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
6.当剩余参数来用(必须放在最后,否则报错)
function test(a,b,...c){
console.log(a); // 1
console.log(b); // 2
console.log(c); // [ 3, 4, 5]
}
test(1,2,3,4,5)
总结:[1,2,3,4] -> ... [1,2,3,4] -> 1,2,3,4,5
1,2,3,4,5 -> ...1,2,3,4,5 -> [1,2,3,4,5]