函数三要素:功能、参数、返回值
1.函数定义和调用
<script>
//1.定义函数
function getSum(m) {
var sum = 0;
for(var i = 0;i<= m;i++){
sum += i;
}
console.log(sum);//55
}
//2.调用函数
getSum(10);
</script>
2.函数返回值
<script>
function getSum(n,m) {
var sum = 0;
for(var i = n;i <= m;i++){
sum += i;
}
return sum;
}
console.log(getSum(1,2)); //3
</script>
3.函数应用
3.1 计算m-n之间的和
<script>
var Sum1= 0 ;
//m,n是形参
function getSum1(m,n) {
for(var i = m;i<= n ;i++ ){
Sum1 +=i;
}
console.log(Sum1);
}
//实参
getSum1(1,2); //3
</script>
3.2 求圆的面积
<script>
function getArea(r) {
//过滤undefined null "" 0 NaN
r= r||0;
var PI = 3.14;
return PI *r *r;
}
console.log(getArea(4)); //50.24
</script>
3.3 求2个数中的最大值
<script>
function getMax(a,b) {
return a>b?a:b;
}
console.log( getMax(10,12)); //12
</script>
3.4 求3个数中的最大值
<script>
function getMax1(a,b,c) {
return (a>b?a:b)>c?(a>b?a:b):c;
}
console.log(getMax1(1,2,3)); //3
</script>
3.5 求数组中最大的值
<script>
function getMax1(a,b,c) {
return (a>b?a:b)>c?(a>b?a:b):c;
}
console.log(getMax1(1,2,3)); //3
</script>
3.6 求数组中最小的值
<script>
function getArrayMin(array) {
array = array || [];
var min = array[0];
for (var i = 1; i < array.length; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
console.log(getArrayMin([1234,12,11,1,34])); //1
</script>
3.7 翻转数组,返回一个新的数组
<script>
function reverseArray(array) {
array = array ||[];
var newArrray = [];
for(var i = array.length -1;i >=0;i--){
newArrray[newArrray.length] = array[i];
}
return newArrray;
}
console.log(reverseArray([1,2,3,4,5]));
</script>
3.8 对数组排序,从小到大
<script>
//6.对数组排序,从小到大
function getSort(array) {
array = array ||[];
//a.外层循环,控制趟数
for(var i = 0 ; i< array.length-1;i++){
var isSort = true;
//b.内层循环,控制比较次数
for(var j = 0; j<array.length-1-i;j++){
//c.判断 比较大小,决定是否交换位置
if(array[j]>array[j+1]){
var temp = array[j];
array[j] = array[j+1];
array[j+1] =temp;
isSort = false;
}
}
//d.判断是否已经完成排序
if (isSort){
break;
}
}
//e.返回数组
return array;
}
console.log(getSort([123,456,78,76,5,43]));
</script>