JavaScript:创建匿名函数

// 将匿名函数赋值给 myFunc
const myFunc = function(param1, param2, ...) {
  // Statements using param1, param2, ...
};

// 调用匿名函数
// param1 value is set to arg1, param2 to arg2, ...
myFunc(arg1, arg2, ...);

另一种方法

// Assignment of an anonymous function to the myFunc variable
const myFunc = (param1, param2, ...) => {
  // Statements using param1, param2, ...
};

// Anonymous function call
// param1 value is set to arg1, param2 to arg2, ...
myFunc(arg1, arg2, ...);

举例

const hello = (name) => {
  const message = `Hello, ${name}!`;
  return message;
};

console.log(hello("William")); // "Hello, William!"

在某些特定情况下,箭头函数语法可以进一步简化:

  • 当函数体中只有一条语句时,所有内容都可以写在同一行而不用花括号。该return语句被省略和隐含。
  • 当函数只接受一个参数时,可以省略它周围的括号。
// Minimalist to the max
const hello = name => `Hello, ${name}!`;

console.log(hello("Kate")); // "Hello, Kate!"
// Say hello to the user
const sayHello = (firstName, lastName) => `Hello, ${firstName} ${lastName}!`;

// Alternative solution using a function declaration
/* function sayHello(firstName, lastName) {
  return `Hello, ${firstName} ${lastName}!`;
} */

const firstName = prompt("Enter your first name:");
const lastName = prompt("Enter your last name:");
console.log(sayHello(firstName, lastName));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值