<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> //计算给定数组arr中所有元素的总和 function sum(arr){ var result = 0; for(var i = 0; i<arr.length;i++){ result = result + arr[i]; } console.log(result); } sum([1,2,3]); //合并数组arr1和数组arr2,不要直接修改数组,结果返回新的数组 function concat(arr1,arr2,arr3){ var arr4 = arr1.concat(arr2,arr3); console.log(arr4); } concat(["s"],["a","b"],[1,3]) //删除数组arr第一个元素,不要直接修改数组arr,结果返回新的数组 function deletes(arr){ var arr2 = arr.slice(0); arr2.shift(); console.log(arr2); } deletes(["s","d","c"]) //在数组arr开头添加元素item,不直接修改数值arr function preAddItem(arr,item){ var arr2 = arr.slice(0); arr2.unshift(item) console.log(arr2); } preAddItem(["a","b","c"],"a"); //移除数组arr中的所有值与item相等的元素,直接在给定数组上操作,并将结果返回 function removeItem(arr,item){ for(var i=0;i<arr.length;i++){ if(arr[i]==item){ arr.splice(i,1); i--; } } console.log(arr); } removeItem(["a","b","c","a"],"a"); //移除数组的第三个元素,并在数组第三个位置添加新元素:(替换元素,把c替换成e,f) //2代表从删除数组元素的开始位置(从何处添加/删除元素。),1代表删除数组是的元素个数,"e""f"代表添加的元素; //array.splice(index,num),num可以为0,即删除0个元素;此方法改变的为原数组内容 function removeAdd(){ var arr = ["a", "b", "c", "d"]; var arrRemove = arr.splice(2,1,"e","f"); console.log(arr); console.log(arrRemove);//输出删除的元素内容,即"c"; } removeAdd(); //找出元素item在给定数组arr中的位置 function indexOf(arr,item){ for(var i = 0;i<arr.length;i++){ if(arr[i] == item){ console.log(i); } } } indexOf(["a","b","c"],"b"); //用数组元素组成字符串 function arrStr(arr){ var arr2 = arr.join(); console.log(arr2) } arrStr(["a","b"]); //删除数组最后一个元素 function removeArrEndItem(){ arr = ["a","b","c"]; var arr2 = arr.pop(); console.log(arr);//在原数组上操作 console.log(arr2);//删除的元素 } removeArrEndItem(); //在数组末尾添加新元素 function addEndItem(){ var arr = ["a","b","c"]; var arr2 = arr.push(); console.log(arr);//在原数组上操作 console.log(arr2);//数组arr的长度 } addEndItem(); //数组排序 function sort(){ var arr = ["c","b","a"]; arr.sort(); console.log(arr); var points = [40,100,1,5,25,10]; points.sort(function(a,b){return a-b}); console.log(points); var points01 = [40,100,1,5,25,10]; points01.sort(function(a,b){return b-a}); console.log(points01); } sort(); //将数组元素转换为字符串输出 function str(){ var fruits = ["Banana", "Orange", "Apple", "Mango"]; var str = fruits.toString(); console.log(str); } str(); </script> </body> </html>
运行结果: