这是我的功能
const accounts = {
a: 100,
b: 0,
c: 20
};
function getAccount() {
let accountName = prompt("Enter an account name");
if (!accounts.hasOwnProperty(accountName)) {
throw new Error(`No such account: ${accountName}`);
}
return accountName;
};
function transfer(from, amount) {
if (accounts[from] < amount) return;
accounts[from] -= amount;
accounts[getAccount()] += amount;
}
如果我尝试像这样调用传输函数
transfer(a,20);
我收到一个错误,“a”未定义,但如果我可以通过这种方式调用函数,它就可以工作
transfer(getAccount(),20);
为什么这个有效而不是前一个?
最佳答案
您需要一个字符串作为值,而不是 undefined variable a
。
transfer('a', 20);
顺便说一句,我添加了异常处理。
const accounts = { a: 100, b: 0, c: 20 };
function getAccount() {
let accountName = prompt("Enter an account name");
if (!accounts.hasOwnProperty(accountName)) {
throw new Error(`No such account: ${accountName}`);
}
return accountName;
}
function transfer(from, amount) {
if (accounts[from] < amount) return;
try {
accounts[getAccount()] += amount;
accounts[from] -= amount; // switch, prevent subtracting if no account
} catch(e) {
console.log(e.name + ': ' + e.message);
}
}
transfer('a', 20);
console.log(accounts);
关于javascript - 为什么我在调用函数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230199/