【问题标题】:Can function expression be used in forEach method?forEach 方法中可以使用函数表达式吗?
【发布时间】:2021-11-21 13:25:48
【问题描述】:

这是我的代码示例:

let arr = [18, 23, 44, 50];
let obj = {
    name: 'Kate',
};
arr.forEach(let func = function(value) {
    console.log(`${this.name} is ${value} years old`);
}, obj); //SyntaxError

所以,看起来我们可以在forEach() 方法中仅使用函数声明和箭头函数。我是对的还是只是错过了什么?

【问题讨论】:

  • 我认为你正在尝试像function printUser(value) { console.log(this.name+' is '+value+' years old'); } arr.forEach(printUser.bind(obj));那样绑定你的obj
  • only function declaration .. 在表达式上下文中声明的函数(例如,在= 符号的右侧,在() 等内部)是一个函数表达式。所以 ONLY 函数表达式可以在 forEach() 中使用,如果您正在编写函数字面量(而不是变量或函数名称),因为当您将函数放入 () 时,它就变成了表达式
  • @slebetman "在表达式上下文中声明的函数(例如,在 = 符号的右侧,inside () 等)是函数表达式.. ." 我不能同意关于() 的部分。我刚刚检查了MDN。函数表达式语法只有一种变体
  • 请问,您这样做有什么原因吗?还是只是出于兴趣?

标签: javascript arrays function object foreach


【解决方案1】:

您可以在没有分配的情况下使用它。名称 (func) 是可选的。

let arr = [18, 23, 44, 50];
let obj = {
    name: 'Kate',
};
arr.forEach(function func(value) {
    console.log(`${this.name} is ${value} years old`);
}, obj);

【讨论】:

    【解决方案2】:

    使用letvarconst,其中需要回调函数的是SyntaxError。您可以删除let,代码将运行良好,或者您可以在forEach 之外声明该函数并在forEach 中调用它,如下所示:

    let func = function(value) {
        console.log(`${this.name} is ${value} years old`);
    };
    arr.forEach(func, obj);
    

    在下面的代码中,我展示了您在 forEach 调用中提供的没有 let 关键字的原始代码,以表明它有效。我还添加了建议的函数声明和相应的forEach 调用。

    let arr = [18, 23, 44, 50];
    let obj = {
      name: 'Kate',
    };
    
    console.log('\tfunc');
    arr.forEach(func = function(value) {
      console.log(`${this.name} is ${value} years old`);
    }, obj);
    
    console.log('\tfunc2');
    let func2 = function(value) {
      console.log(`${this.name} is ${value} years old`);
    };
    arr.forEach(func2, obj);

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多