数组练习
1、数组的遍历
<script>
//数组的遍历
var arr1=['蒲熠星','Stefan','郭文韬','Qiao'];
for(var i=0;i<4;i++){
console.log(arr1[i]);//i是计数器,用来当索引index
}
var arr2 = ['蒲熠星','郭文韬','刘小怂','JY','少帮主'];
arr2.length=3;
console.log(arr2);
/* for(var i=0;i<arr2.length;i++){
console.log(arr2[i]);
} */
</script>
2、数组的反转
<script>
var arr = [1, 2, 3, 4, 5, 6, 7];
var arr1 = [];
for (var i = 6; i >= 0; i--) {
arr1[arr1.length] = arr[i];
}
console.log(arr1);
</script>
3、冒泡排序
<script>
var arr = [6, 1, 99, 8, 5];
var mum = arr[0];
for (var i = 0; i < arr.length - 1; i++) {//外重循环是趟数
for (var j = 0; j < arr.length - 1 - i; j++) {//内重循环是 一趟两两比较的次数
if (arr[j] > arr[j + 1]) {
//两个变量交换数值的方法
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
alert(arr);
</script>
4、数组转化成字符串
<script>
var arr = ['i', 'love', 'china']; //转化成字符串
/* var s = arr.join("*");
console.log(s);
console.log(typeof s); */
var str = '';
var star = '*';
for(var i=0;i<arr.length;i++){
/* var s = arr[i].toString(); */
str += arr[i]+star;
}
console.log(str);
</script>
5、求数组中的最大值
<script>
var arr = [1, 6, 99, 56, 4, 100, 34];
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log(max);
</script>
6、筛选数组中大于20的数
<script>
var arr = [4, 0, 45, 0, 1, 23, 34, 0, 56, 101, 67];
//把数组中大于20的数筛选出来,放到一个新数组
var num = 20;
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > 20) {
arr2[arr2.length] = arr[i];
}
}
console.log(arr2);
</script>
7、计算和与平均值
<script>
var arr1 = [1, 3, 5, 7, 9];
var sum = 0;
var average = 0;
for (var i = 0; i < arr1.length; i++) {
sum += arr1[i];
average = sum / 5;
}
console.log(sum);
console.log(average);
</script>
8、空数组存1-100的值
<script>
var arr = [];
for(var i = 0;i<100;i++){
arr[i]=i+1;
}
</script>