add 6.2 and 6.3

This commit is contained in:
Hanzhang ma 2024-06-22 23:54:56 +02:00
parent 7bec5f3111
commit fcc6ef2a49
2 changed files with 86 additions and 0 deletions

47
6.2RestSpread/t.js Normal file
View File

@ -0,0 +1,47 @@
console.log("Rest and Spread Operator");
console.log("Rest Operator");
// Rest Operator
function sumAll(...args){
let sum = 0;
for(let arg of args){
sum += arg;
}
return sum;
}
console.log(sumAll(1,2,3,4,5));
function showName(firstName, lastName, ...titles) {
console.log( firstName + ' ' + lastName ); // Julius Caesar
// 剩余的参数被放入 titles 数组中
// i.e. titles = ["Consul", "Imperator"]
console.log( titles[0] ); // Consul
console.log( titles[1] ); // Imperator
console.log( titles.length ); // 2
}
showName("Julius", "Caesar", "Consul", "Imperator");
console.log("Attention: Rest parameters should be at the end");
console.log("Attention: Only one rest parameter is allowed");
consoel.log("Attention: Arrow functions do not have 'arguments' object");
console.log("Spread Operator");
// Spread Operator
let arr = [3, 5, 1];
console.log(Math.max(arr)); // NaN
console.log(Math.max(...arr)); // 5
let arr1 = [1, -2, 3, 4];
let arr2 = [8, 3, -8, 1];
console.log(Math.max(...arr1, ...arr2)); // 8
let merged = [0, ...arr1, 2, ...arr2];
console.log(merged);
console.log("Attention: Spread operator can be used to merge arrays");
console.log("Attention: Spread operator can be used to convert string to array");
console.log("Attention: Spread operator can be used to convert arguments to array");

39
6.3variablescope/t.js Normal file
View File

@ -0,0 +1,39 @@
function sum(a){
return function(b){
return a + b;
}
}
console.log(sum(1)(2));
console.log(sum(5)(-1));
function byField(Field){
return (a,b) => a[Field] > b[Field]? 1: -1;
}
function makeArmy() {
let shooters = [];
let i = 0;
while (i < 10) {
let id = i;
let shooter = function() { // 创建一个 shooter 函数,
console.log( id ); // 应该显示其编号
};
shooters.push(shooter); // 将此 shooter 函数添加到数组中
i++;
}
// ……返回 shooters 数组
return shooters;
}
let army = makeArmy();
// ……所有的 shooter 显示的都是 10而不是它们的编号 0, 1, 2, 3...
army[0](); // 编号为 0 的 shooter 显示的是 10
army[1](); // 编号为 1 的 shooter 显示的是 10
army[2](); // 10其他的也是这样。