数组元素求和求平均值
javascript"> let sum = 0
let ave = 0
let a = [2,6,1,7,4]
for(i = 0 ; i < 5 ; i ++ ) {
sum += a[i]
}
ave = sum / 5
document.write(sum+'<br>')
document.write(ave)
数组求最大值和最小值
javascript"> let a = [2,6,1,77,52,25,7,0,77]
let max = 0
let min = Number.MAX_VALUE
for(i = 0; i < a.length ; i ++ ) {
if(a[i] >= max){
max = a[i]
}
else if(a[i] <= min) {
min = a[i]
}
}
document.write(max + '<br>' + min)
数组筛选
要求
将数组 [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] 中大于等于 10 的元素选出来,放入新数组
代码
javascript">let a = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7]
let newArray = []
for(i = 0;i < a.length ; i ++ ) {
if(a[i] >= 10 ) {
newArray.push(a[i])
}
}
document.write(newArray)
数组去0
要求
将数组 [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] 中的 0 去掉后,形成一个不包含 0 的新数组
代码
javascript">let a = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7]
let newArray = []
for(i = 0;i < a.length ; i ++ ) {
if(a[i] != 0 ) {
newArray.push(a[i])
}
}
document.write(newArray)