<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
//计算数组arr中所有元素的和
//例如:输入sum([1,2,3,4]),输出10
//方法一:
function sum(){
var all=0;
for (var i=0;i<arguments.length;i++) {
if (typeof(arguments[i]=="number")) {
all+=arguments[i];
}
}
return all;
}
document.write(sum(1,2,3,4)+'<br/>');
//方法二:
function sum2(arr){
var all=0;
for (var i=0;i<arr.length;i++) {
if (typeof arr[i]=="number") {
all+=arr[i];
}
}
return all;
}
document.write(sum2([1,2,3,4]));
//方法三:
var arr1=[1,2,3,4,5,6,7,8,9];
var sum1=0;
for (var i=0;i<=arr1.length;i++) {
if (typeof arr1[i]=="number") {
sum1+=arr1[i];
}
}
document.write(sum1);
</script>
</html>