/*利用循环遍历数组*/ var arr = [1,2,3,4,5] for(var i = 0;i<arr.length;i++){ console.log(arr[i]); } /*数组案例——求所有元素的和*/ var arr1 = [1,2,3,4,5],sum=0; for(var i = 0;i<arr1.length;i++){ sum += arr1[i]; } console.log(sum); /*求数组中的最大值*/ var arr2 = [1,2,3,4,5,10],max = arr2[0]; for(var i = 1;i<arr2.length;i++){ if(arr2[i]>max){ max = arr2[i]; } } console.log(max); /*最小值与上面相似*/ /*倒叙遍历数组*/ var arr3 = [1,2,3,4,5,6]; for(var i = arr3.length-1;i >= 0;i--){ console.log(arr3[i]); } /*字符转拼接*/ var arr4 = [‘李小龙‘,‘叶问‘,‘黄飞鸿‘]; var str = ‘‘; for(var i = 0; i<arr4.length-1;i++){ str += arr4[i]+‘||‘; } console.log(str+arr4[arr4.length-1]);
/*去除数组中的0*/ var arr6 = [2, 0, 5, 0, 7, 3, 0, 4]; //新数组 var t = []; for(var i = 0; i < arr6.length; i++) { if(arr6[i] != 0) { // console.log(arr6[i]); //插入新数组 t[t.length] = arr6[i]; } } console.log(t);