2017-05-04 45 views
0

我是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

+1

'input'是一個字符串,它沒有'forEach'方法,因此錯誤是預期的。 – Satpal

+0

爲什麼'input'是一個字符串,如果我特別提示它爲'array'? – borgmater

+1

請參閱[prompt()](https://developer.mozilla.org/en/docs/Web/API/Window/prompt),_result是一個包含用戶輸入的文本的字符串,或null._ – Satpal

回答

1

輸入變量將採取字符串。 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)); 
0

forFeach API需要一個arrayinputstring而不是array

function sumArray(arr){ 
    var sum = 0; 
    arr.forEach(function(element){ 
     sum+=element; 
    }); 
    return sum; 
} 

var responses = []; 
var input = prompt("Give array"); 
responses.push(input) 
console.log(sumArray(responses)); 
相關問題