使用for循环、while循环和递归写出3个函数来计算给定数列的总和。

颜鸿羽
浏览 1385回答 1
1回答

QQ_随意

var arr = [1,"2","asfda3afs",4,5,6,7,8,9]function forFun(arr) { let num = 0; for(let i = 0 ; i < arr.length ; i++) { if(typeof arr[i] !== "number"){ num = num + parseFloat(arr[i].replace(/[^0-9]/ig,"")); }else{ num = num + arr[i]; } } return num;}function whileFun(arr) { let num = 0; let arr1 = Array(...arr); while(arr1.length > 0){ let val = arr1.pop(); if(typeof val !== "number"){ num = num + parseFloat(val.replace(/[^0-9]/ig,"")); }else{ num = num + val; } } return num;}function Fun(arr) { let num = 0; let arr1 = Array(...arr); function reFun () { if(arr1.length > 0){ let val = arr1.pop(); if(typeof val !== "number"){ num = num + parseFloat(val.replace(/[^0-9]/ig,"")); }else{ num = num + val; } reFun(); }else{ return } } reFun (); return num;}console.log(forFun(arr))console.log(whileFun(arr))console.log(Fun(arr))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript