js入门之数组

 

数组是一种数据类型,数组可以存储很多项, 有序,集合 Array

定义: var names = ['zs','ls','ww','zl']
访问: 用索引或/下标
数组可以存储多种类型的数据 但是一般存储的都是一中类型
数组的长度:
    var names = ['zs','ls','ww','zl']
        console.log(names.length);

获取数组中最后一项的索引 (数组的长度-1)
console.log(names[names.length -1]);

数组的长度可以动态改变
names[0] = 'xxx';  修改
如果索引不存在 则会直接追加 如果不连续添加 中间的值默认会是undefined

获取数组中的每一项,并打印(遍历数组 forvar names = ['zs','ls','ww','zl']
    for (var i = 0; i < names.length; i++){
        console.log(names[i]);
    }

或者数组从最后开始打印
    var names = ['zs','ls','ww','zl']
    for (var i = names.length-1; i>=0; i--) {
        console.log(names[i]);
    }
清空数组
scores.length = 0;

求数组的和 和平均值案例

var numbers = [100,200,300];
    var sum =0;
    var avg;
    for (var i = 0; i < numbers.length; i++) {
        sum += numbers[i]
    }
    avg = sum/(numbers.length)
    console.log(sum)
    console.log(avg)
View Code

查找一个数组中的最大值和最小值已经其索引

var numbers = [100,200,500,400];
    var max = numbers[0];
    var min = numbers[0];
    var maxInde = 0;
    var minIndex = 0;
    for (var i = 1; i < numbers.length; i++) {
        if (max < numbers[i]) {
            max = numbers[i];
            maxIndex = i;        
        }
        if (min > numbers[i]) {
            min = numbers[i]
            minIndex = i;
        }
    }
    console.log(maxIndex, max)
    console.log(minIndex, min)
View Code

将字符串数组用|分割

var names = ['大华','洋洋','李易峰','胡歌','刘亦菲']
    seperator = '|';
    var str = names[0];
    for (var i = 1; i<=names.length-1; i++) {
        str += str = seperator + names[i];
    }
    console.log(str)
View Code

筛选出数组里面非0的字符串 然后放到一个新的数组里

var new_numbers = [];
    var numbers = [5,4,6,0,11,33,5,0];
    for (i = 0; i < numbers.length; i++) {
        if (numbers[i] !== 0) {
            new_numbers[new_numbers.length] = numbers[i];
        }
    }
    console.log(new_numbers);
View Code

翻转数组 然后放入一个新的数组里面

var new_numbers = [];
    var numbers = [1,2,3,4,5];
    for (var i = numbers.length-1; i>= 0; i-- ) {
        new_numbers[new_numbers.length] = numbers[i]
    }
    console.log(new_numbers)
View Code

冒泡排序

var numbers=[97,68,72,29,51,45];
    //外层循环 控制次数 每一次找到一个最大值
    for (var i = 0; i < numbers.length - 1; i++) {
        //内层循环 控制比较的次数,并且判断两个数的大小,把大的外后移
        for (var j = 0; j< numbers.length -1 -i; j++) {
            //两两比较 从小到大
            if (numbers[j] > numbers[j+1]) {
                //交换位置
                var tmp = numbers[j];
                numbers[j] = numbers[j+1];
                numbers[j+1] = tmp;
            }
        }
    }
    console.log(numbers)
View Code

 

posted @ 2019-12-04 18:15  ivy_wang  阅读(185)  评论(0编辑  收藏  举报