遍历一个数组
var arr = [3, 6, 4, 99, 88, 67, 52, 26, 10]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//
计算一个数组的和以及平均值
<script>
var sum = 0;
var everage = 0;
var arr = [3, 5, 9, 8, 1, 99, 55, 34, 61, 28];
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
everage = sum / arr.length;
console.log(sum,everage);
</script>
//
打印一个数组中的最大值
var arr = [3, 5, 9, 8, 1, 99, 55, 34, 61, 28];
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log(max);
//
把一个数组的元素都取出来分别定义为字符串,放进一个新数组
var arr = [3, 5, 9, 8, 1, 99, 55, 34, 61, 28];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr[newArr.length] = String(arr[i]);
}
console.log(newArr);
//
把一个数组转化成一个字符串,加上竖线:|
var arr = ['pink', 'red', 'yellow', 'blue'];
var str = '';
for (var i = 0; i < arr.length; i++) {
str += arr[i] +'|';
}
console.log(str);
//
把一个数组转化成一个字符串
var arr = [3, 5, 9, 8, 1, 99, 55, 34, 61, 28];
str = '';
for (var i = 0; i < arr.length; i++) {
str += arr[i];
}
console.log(str);
//
翻转数组
var arr = [3, 5, 9, 8, 1, 99, 55, 34, 61, 28];
var newArr = [];
var j = 0;
for (var i = arr.length - 1; i >= 0; i--) {
newArr[j] = arr[i];
j++;
}
console.log(newArr);
//
冒泡排序
var arr = [5, 9, 3, 2, 6, 0];
var temp;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j <= arr.length - i - 1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
console.log(arr);