我不明白我爲什麼得到"Uncaught TypeError: ops is not a function"
而ops
持有multiply
因此ops()
解決爲multiply()
和功能multiply()
是在範圍內定義。Javascript:存在與變量值同名的函數,但接收typeError,爲什麼?
var product = 1;
var sum = 0;
var x = parseInt(prompt("Enter a No. ", 10));
var ops = prompt("Addition/ Multiplication", "multiply");
var y = x;
var operation_type = function (ops){
var ops = ops;
return ops;
}
var ops = operation_type(ops);
// console.log(ops);
console.log(ops(x));
// ops(x);
function addition (x) {
for (i=0; i< x; i++) {
sum = sum + y;
y = y - 1;
}
sum = "Recursive sum of " + x + " is: " + sum;
document.getElementById('result').innerHTML = sum;
}
function multiply(x) {
for (i=0; i< x; i++) {
product = product*y;
y = y - 1;
}
product = "Recursive Product of " + x + " is: " + product;
document.getElementById('result').innerHTML = product;
}
感謝 BT
您在ops中給出參數,所以它是函數。並且ops函數不存在 – Mahi
'promt'只返回字符串(或null),而不是函數。很明顯'ops'不是一個函數。 – Oriol
參見'var ops = operation_type(ops);''這意味着js fun'operation_type(ops)'將執行並返回值到'ops'在非常nex行中,您嘗試執行它作爲函數,但'ops'是變量,而不是函數這就是爲什麼你會得到這樣的錯誤。 – Veer