批改状态:合格
老师批语:
<script defer src="test.js"></script>
总之,放在</body>标签前就可以
占位符
console.log(“用户名:%s, 密码:%s”,user.name,user.password)
let obj = {id: 0001,age: 22,name: "hehe"}console.log("Using console.log()");console.log(obj);console.log("---------------------");console.log("Using console.table()");console.table(obj);console.log("---------------------");console.log("Using console.dir()");console.dir(obj);

let name = "HaHa";function getName(name) {return "My name is " + name;}console.log(getName(name));
输出:

let name = "HaHa";function getName(name) {return "My name is " + name;}function getName(name) {return "我的名字是 " + name;}console.log(getName(name));
输出:

命名的函数声明会被自动提示,即先调用后声明也可以
let name = "HaHa";console.log(getName(name));// function declarationfunction getName(name) {return "My name is " + name;}
输出:

使用匿名函数
let sum = function (a, b) {return a + b;}console.log(sum(1, 2));//3
let sum = function (a, b = 2) {return a + b;}console.log(sum(1));//3
rest语法,将所有参数放到数组中
let summary = function (...arr) {let e = 0;for (let index = 0; index < arr.length; index++) {e += arr[index];}return e;}console.log(summary(1, 9, 2, 8, 3, 7, 4, 6, 5));//45
使用数组或对象的形式返回
function getUser() {return [20, "Tom", "tom123"];}console.table(getUser());function getAddress() {return { room: 0101, street: "Goodwood Road", post: 5000 };}console.table(getAddress());

将函数作为参数,或使用函数作为返回值的函数
function foo(p) {//console.log(p)return function () {return "a";};}let f = foo(function () { });console.log(f());//a
函数作为参数
document.addEventListener("click", function () {alert("hehe");});
//声明sum = function (a) {return function (b) {return function (c) {return function (d) {return a + b + c + d;}}}};//调用let result = sum(1)(2)(3)(4);console.log(result);//10
function getPrice(p, n) {return p * n;}getPrice(10, 5);
let sum = function (a, b) {return a + b;}console.log(sum(1, 2));//箭头函数简化匿名函数sum = (a, b) => {return a + b;}console.log(sum(2, 3));//如果箭头函数的代码体只有一行语句sum = (a, b) => a + b;console.log(sum(3, 4));
*如果函数中使用到this关键字,就不要使用箭头函数,不能当构造函数使用
声明和调用放在一起
(function(p, n) {console.log(p * n)})(5, 10);//50let sum = function (a, b) {return a + b;}(1, 2);console.log(sum);//3
*在过去,立即执行函数可以用来防止函数内的局部var变量作用域提升到全局
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号