每个人...
我有一个class
。
我不明白为什么突然在getName
这个类的方法中该方法的行为很奇怪Array.map()
要查看问题,请取消注释底行并注释掉最上面的行。
唯一的区别在于{}
花括号。
但是getData()
不存在这样的问题...
//const arrayHtml = fs.readdirSync(path.resolve(__dirname, templateDir));
const arrayHtml = ['index.html', 'dash.html', 'zoo.html'];
class DataSiteConfig {
constructor(folder, favicon) {
this.name = name;
this.favicon = favicon;
this.folder = folder;
this.pageList = [];
}
getName(dirNameFiles) {
this.name = dirNameFiles.map((s, i, arr) => s.slice(0, -5));
//this.name = dirNameFiles.map((s, i, arr) => {s.slice(0, -5)});
}
getData() {
this.name.map((s, i, arr) => {
this.pageList.push({
title: s,
template: `frontend/html/${s}.html`,
filename: `pages/${s}.html`
})
})
}
}
let dataSiteConfig = new DataSiteConfig('Zona', 'Chtoto.png');
dataSiteConfig.getName(arrayHtml);
dataSiteConfig.getData();
console.log("TCL: dataSiteConfig", dataSiteConfig);
谁能告诉我为什么...
您的语法略有错误。箭头函数的主体可以是简明主体或块主体。这个选项:
之所以有效,是因为在箭头函数中,如果我们需要返回一行写的内容,我们可以省略括号。这类似于写作:
如果你写了括号并且没有指定
return
,那么它将被返回undefined
,完整的形式看起来像这样:因此,数组的每个元素都是
undefined
.中的代码
getData()
可以正常工作,因为那里没有返回任何内容,但只是传递了循环。在那里使用根本没有多大意义map()
,因为它map()
返回一个修改后的数组,并且getData()
正常通过整个数组。MDN 文档:箭头函数