
批改狀態(tài):合格
老師批語:
return 字符串/變量/表達(dá)式;
function webShell(...shell) {
return shell;
}
let hack = ["or", "=", "or"];
console.log(webShell(...hack));
obj = () => ({
a: 1,
b: 2,
c: function () {
return null;
},
});
// 參數(shù)
function web(website) {
return website;
}
// 返回值默認(rèn)是單值:return website;
console.log(web("https://www.xxx.com"));
// 使用...rest返回多個(gè)返回值(數(shù)組,對(duì)象)
function webShell(...shell) {
return shell;
}
let hack = ["or", "=", "or"];
// ...rest使用在調(diào)用函數(shù)時(shí),會(huì)展開容器["or", "=", "or"] === "or" , "=" , "or"
console.log(webShell(...hack));
obj = () => ({
a: 1,
b: 2,
c: function () {
return null;
},
});
console.log(obj());
用反引號(hào)(`)標(biāo)識(shí)。它可以當(dāng)作普通字符串使用,也可以用來定義多行字符串,或者在字符串中插入變量/表達(dá)式
插值:使用占位符${變量/表達(dá)式}
將動(dòng)態(tài)值放入創(chuàng)建的字符串中
let num = 8;
let insertValue = `我是模板字符串,${num}我也是模板字符串,${
8 * 8}`;
let doubleLine = `
我是第一行
我是第二行
`;
console.log(insertValue);
console.log(doubleLine);
模板函數(shù)/標(biāo)簽 :是將模板字面量作為實(shí)參,傳給一個(gè)函數(shù)
標(biāo)簽函數(shù)的第一個(gè)參數(shù)是一個(gè)數(shù)組,里面是沒有${}占位符所替換的部分,也就是模板字符串中的所有字面量,就是說這里形參接收的是模板字符串中除去${}之外的字符串所組成的數(shù)組,每一個(gè)${}都相當(dāng)于一個(gè)分隔符
第二個(gè)是剩余參數(shù),包含了所有${}占位符中的計(jì)算結(jié)果,而想要接收${}所表示的字符串,需要額外的形參,有幾個(gè)${}就需要多幾個(gè)形參,或者使用rest參數(shù)來把剩余的參數(shù)接收為一個(gè)數(shù)組,形式為:函數(shù) (形參1 ,...形參2)
function f(a) {
console.log(a);
}
f`我會(huì)被傳遞給第一個(gè)形參,${"我不會(huì)被第一個(gè)形參傳遞"},8也會(huì)`;
let str1 = "我被形參b接收";
let str2 = "我被形參c接收";
function tag(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
tag`我被第一個(gè)形參傳遞,${str1},我也被第一個(gè)形參傳遞,${str2}`;
// 函數(shù)常規(guī)調(diào)用
tag(1, 2, 3);
function fun(a) {
function fun2(b) {
return a + b;
}
// 函數(shù)加了括號(hào)就是調(diào)用,所以不能加括號(hào)
// return fun2();
return fun2;
}
console.log(fun(2)(3));
簡(jiǎn)單來說,閉包就是在一個(gè)函數(shù)當(dāng)中再嵌套一個(gè)函數(shù),內(nèi)層函數(shù)可以訪問外層函數(shù)中聲明和定義的變量,而外層函數(shù)卻不能訪問內(nèi)層函數(shù)中聲明和定義的變量,內(nèi)層函數(shù)向?qū)τ谕鈱雍瘮?shù)來說是封閉的,所以當(dāng)在一個(gè)函數(shù)中還定義了一個(gè)函數(shù),內(nèi)層函數(shù)是一個(gè)閉包
某個(gè)變量的變量名和對(duì)象某個(gè)屬性同名,且在一個(gè)作用域,可以給對(duì)象字面量簡(jiǎn)化
let arr = {
name: "pharaoh",
age: 30,
height: 172,
sum: function () {
return this.age + this.height;
},
};
console.log(arr.sum());
// 簡(jiǎn)化
let name = "Pharaoh";
let age = 30;
let height = 172;
let arr2 = {
name,
age,
height,
// 方法簡(jiǎn)寫:去掉冒號(hào)和function (: function)
sum() {
return this.age + this.height;
},
sum1: () => arr2.age + arr2.height,
// 不要再箭頭函數(shù)中使用this
// this在普通函數(shù)中,調(diào)用時(shí)確定
// this在箭頭函數(shù)中,聲明時(shí)確定
// sum1: () => this.age + this.height,
};
console.log(arr2.sum());
console.log(arr2.sum1());
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)