【问题标题】:What are the f and i parameters passed to callback of forEach?传递给 forEach 回调的 f 和 i 参数是什么?
【发布时间】:2018-08-16 10:32:09
【问题描述】:

这段代码中的“i”和“f”是什么意思?它是如何定义的+代码如何知道它的文件名和文件数量?

if(err) console.log(err);

let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
    console.log("couldn't find commands.");
    return;
}

jsfile.forEach((f, i) =>{
    let props = require(`./commands/${f}`);
    console.log(`${i} commands have loaded!`);
    bot.commands.set(props.help.name, props);
});

【问题讨论】:

  • 它正在编辑,我不知道我怎么忘记代码了哈哈
  • 那么jsfile 是什么?
  • f & i 它们只是数组 forEachfunction.Google 的数组 forEach 的参数,你会知道的

标签: javascript foreach


【解决方案1】:

forEach 迭代 jsfiles 变量的项目 - 这是通过过滤 files 生成的数组。 f 是数组中的项,if 在集合中的索引。

您可以阅读有关Array.prototype.forEach hereArray.prototype.filter here 的更多信息。


为了给你一个关于forEach 用法的例子,考虑下面sn-p 中的items 是一个数组。注意参数itemindex对应实际项,以及它在数组中的索引:

var items = ["Item 1", "Item 2", "Item 3"];

items.forEach((item, index) => {
  console.log(item, "#", index);
});

【讨论】:

  • jsfile如何定义为数组?
  • let jsfile = files.filter(f =&gt; f.split(".").pop() === "js")
  • 那么在 let jsfile = files.filter(f => f.split(".").pop() === "js") 中的哪里使它成为一个数组?我认为数组使用方括号? []
  • @TimothyChell 避免变色龙问题,即避免编辑问题以提出更多“问题”。它使现有答案无效。
  • @TimothyChell files 必须是一个数组。当你filter 时,结果仍然是一个数组。当然,在某些时候,可能已经使用方括号定义了数组,但这不是必需的。例如考虑var x = Object.keys({})。所以files 数组也可能是通过其他方法在别处生成的。
猜你喜欢
  • 2015-06-15
  • 2013-12-01
  • 2012-08-23
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
相关资源
最近更新 更多