一、定义一个数组把其中的偶数取出,组成一个新的数组
var attr = [9,34,80,27,56]; var attr1 = []; for(var i in attr){ if(attr[i] % 2 == 0){ attr1[attr1.length] = attr[i]; 或者(attr1.push(attr[i]);) } } console.log(attr1);
二、定义一个数组把其中的最大值、最小值和其标签取出来
var attr = [9,3,4,80,70,67,56]; var maxattr = attr[0]; var minattr = attr[0]; var maxlength = 0; var minlength = 0; for(var i in attr){ if(attr[i] > maxattr){ maxattr = attr[i]; maxlength = i; } if(attr[i] < minattr){ minattr = attr[i]; minlength = i; } } document.write(maxattr + "、" + maxlength + "、" + minattr + "、" + minlength)
三、将数组中数字内容求和var attr = [12,34,2,5,76];
var attr = [12,34,2,5,76]; var sun = 0; for(var i in attr){ sun += attr[i]; } alert(sun);
四、var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];要求将数组中的0项去掉,将不为0的值存入一个新的数组,生成新的数组
var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0]; var new1 = []; for(var i = 0;i < arr.length;i++){ if (arr[i] != 0) { new1[new1.length]= arr[i];/*(new1.length为数组当前长度,每循环一次,数组长度+1)*/ 或者(new1.push(arr[i]) } } alert(new1);
原文地址:https://www.cnblogs.com/mjwwzy/p/9033642.html
时间: 2024-10-14 17:11:02