I'm just learning ES6 and learned about arrow functions. I'm going through an existing file and converting functions one by one. I've converted numerous functions and all have worked as they did previously with the exception of 1.
Doing this, I can call page
to get the current filename
let textArr = getPage.textArr;
let headingArr = getPage.headingArr;
const page = getPage.filename;
function getPage() {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
Leaving everything as is, converting to an arrow function, then calling page
in console, I get:
getPage is not defined at line 1
const getPage = () => {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
答案 0 :(得分:3)
您实际上不是在调用函数,即const page = getPage().filename;
应该替换为let {textArr, headingArr, textArr} = getPage();
对于所有三个变量,您可以执行以下操作:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
答案 1 :(得分:3)
It's a hoisting problem. Functions are hoisted by default. That is not happening to arrow functions assigned to a variable. If you want that to work, you need to move the const definition before you call it. Like this:
const getPage = () => {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
let textArr = getPage().textArr;
let headingArr = getPage().headingArr;
const page = getPage().filename;
答案 2 :(得分:2)
再添加1个大括号即可使用。
const getPage = () => {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.');
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}