我是JS初學者,偶然發現了一個我無法弄清的問題。標題錯誤出現我跑在崇高這個簡單的加和功能後:Uncaught TypeError:arr.forEach不是函數
HTML
<!DOCTYPE html>
<html>
<head>
<title>JS Exercise</title>
<script src="JSexercise.js"></script>
</head>
<body>
<h1>JS Exercise</h1>
</body>
</html>
JS
function sumArray(arr){
var sum = 0;
arr.forEach(function(element){
sum+=element;
});
return sum;
}
var input = prompt("Give array");
console.log(sumArray(input));
錯誤
Uncaught TypeError: arr.forEach is not a function at sumArray (JSexercise.js:3) at JSexercise.js:10
'input'是一個字符串,它沒有'forEach'方法,因此錯誤是預期的。 – Satpal
爲什麼'input'是一個字符串,如果我特別提示它爲'array'? – borgmater
請參閱[prompt()](https://developer.mozilla.org/en/docs/Web/API/Window/prompt),_result是一個包含用戶輸入的文本的字符串,或null._ – Satpal