1.模板字符串可以\转义
const str = `Hello 2020,It was a \`beautiful\` day `;
console.log(str);//Hello 2020,It was a `beautiful` day
2.可以换行
image3.把js片段输出,不用+号拼接
const name = 'clover';
const msg = `hi,${name}--${1+2}--${Math.random()}`;
console.log(msg);//hi,clover--3--0.8134929903779471
- 带标签的模板字符串
function printMsg(msg,name,age) {
console.log(msg, name, age);//[ 'hi,', ' is ', '.' ] clover 18
return age>16?'花季':'雨季';
};
const name = 'clover';
const age = 18;
const str = printMsg`hi,${name} is ${age}.`;
console.log(str);//花季
- 字符串的扩展方法
- includes()
- startsWith()
- endsWith()
const message = 'Error:foo is not design';
console.log(message.startsWith('error'));//false
console.log(message.startsWith('Error'));//true
console.log(message.endsWith('.'));//flase
console.log(message.endsWith('design'));//true
console.log(message.includes('not'));//true
6.参数默认值,默认值在不传或者传参为undefined的时候生效,带有默认值的参数,放在最后,否则调用时候有误
function isShow(flag = true) {
console.log(flag);
}
isShow();//true
isShow(false);//false
isShow(undefined);//true
- 剩余参数...只能放在最后
function foo(first,...args) {
console.log(args);//[2,3,4]
};
foo(1, 2, 3, 4);
- 展开数组
const arr = [1, 2, 3, 4];
//打印数组每一个 之前做法
console.log.apply(console, arr);//1,2,3,4
//现在用展开数组...
console.log(...arr);//1,2,3,4
- JSON.stringify()的几种妙用
/判断数组是否包含某对象
let data = [
{name:'clover'},
{name:'肖战'},
{name:'朱一龙'},
],
val = {name:'肖战'};
JSON.stringify(data).indexOf(JSON.stringify(val)) !== -1;//true
//判断两数组/对象是否相等
let a = 1,2,3],
b = [1,2,3];
JSON.stringify(a) === JSON.stringify(b);//true
let ac = [{a:1,b:2,c:3}],
bc = [{a:1,b:2,c:3}];
JSON.stringify(ac) === JSON.stringify(bc);//true
ac = [{a:2,b:2,c:3}];
JSON.stringify(ac) === JSON.stringify(bc);//false
//存储localStorage/sessionStorage存储对象。
function setLocalStorage(key,val){
window.localStorage.setItem(key,JSON.stringify(val));
};
//读取字符串转为对象
function getLocalStorage(key){
let val = JSON.parse(window.localStorage.getItem(key));
return val;
};
//测试
setLocalStorage('item',[1,2,3]);
let a = getLocalStorage('demo');//[1,2,3]
网友评论