我是一个 JS 初学者,偶然发现了一个我无法解决的问题。我在 Sublime 中运行这个简单的 sum 函数后出现标题错误:
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
最佳答案
输入变量将采用字符串。 split() 用于将字符串转换为数组。因此,首先根据您在提示中传递的分隔符分割字符串,这将输出一个数组。然后将此数组传递给函数 sumArray。
var input= "1 2 3 4 5"; // Enter 1 2 3 4 5 in prompt box
// Split the string by whitespaces - arr will now contain [1,2,3,4,5]
var arr = input.split(" ");
console.log(sumArray(arr));
关于javascript - 未捕获的 TypeError : arr. forEach 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43780861/