[英]Callback function, how to increment number from object then add to sum property
Where am i wrong?我哪里错了? I want to increment firstNumber then I want sum result to be 2. When I tried to debug and I got error "x is not defined"我想增加 firstNumber,然后我希望总和结果为 2。当我尝试调试时,我收到错误“x 未定义”
function main() {
let object = {
firstNumber: 1,
sum: 0
}
secFun(x, object, firstFun)
console.log(object.sum)
}
function firstFun(a) {
a.firstNumber++;
a.sum += a.firstFun;
}
function secFun(x, y, callback) {
callback(x, y);
}
main();
Your main()
function is calling secFun with parameter x
, but you have not declared x
within the function's scope.您的main()
function 正在使用参数x
调用 secFun,但您尚未在函数的 scope 中声明x
。
In fact, you have not declared x
anywhere.实际上,您还没有在任何地方声明x
。
function main() {
let object = {
firstNumber: 1,
sum: 0
}
// 'x' is not defined in local or global scope
secFun(x, object, firstFun)
console.log(object.sum)
}
In additon, your secFun
function calls a callback with two parameters, but firstFun
accepts only one parameter.此外,您的secFun
function 调用带有两个参数的回调,但firstFun
只接受一个参数。
function secFun(x, y, callback) {
// calling 'callback' with two arguments
callback(x, y);
}
// but firstFun accepts only one parameter
function firstFun(a) {
}
function firstFun(a) {
a.firstNumber++;
a.sum += a.firstNumber;
}
function secFun(x, callback) {
callback(x);
}
function main() {
let object = {
firstNumber: 1,
sum: 0
}
secFun(object, firstFun)
console.log(object)
}
main();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.