2、二维数组与对象数组


// 创建二维数组
Array.matrix = function(numrows, numcols, initial){
    var arr = [];
    for(var i=0; i<numrows; ++i){
        var columns = [];
        for(var j=0; j<numcols; ++j){
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

var nums = Array.matrix(5, 5, 0);
console.log(nums[1][3]);

var names = Array.matrix(3, 3, "");
names[1][2] = "Joe";
console.log(names[1][2]);

// 处理二维数组的元素
var grades = [[89, 77, 78], [76, 82, 81], [91, 94, 89]];
var total = 0;

for(var i=0; i<grades.length; ++i){
    for(var j=0; j<grades[i].length; ++j){
        total += grades[i][j];
    }
    var average = total / grades[i].length;
    console.log("Student"+parseInt(i+1)+"的平均成绩是:" + average.toFixed(2));
    total = 0;
}

for(var i=0; i<grades.length; ++i){
    var total = 0;
    for(var j=0; j<grades[i].length; ++j){
        total += grades[j][i];
    }
    var average = total / grades[i].length;
    console.log("Test"+parseInt(i+1)+"的平均成绩是:" + average.toFixed(2));
    total = 0;
}

// 对象数组
function Point(x, y){
    this.x = x;
    this.y = y;
}

function displayArr(arr){
    for(var i=0; i<arr.length; ++i){
        console.log(arr[i].x + " - " + arr[i].y);
    }
}

var p1 = new Point(1, 2);
var p2 = new Point(11, 22);

var points = [p1, p2];
displayArr(points);

var p5 = new Point(123, 44);
points.push(p5);
displayArr(points);

points.shift();
displayArr(points);

// 对象中的数组
function weekTemps(){
    this.dataStore = [];
    this.addFunc = addFunc;
    this.averageFunc = averageFunc;
}

function addFunc(temp){
    this.dataStore.push(temp);
}

function averageFunc(){
    var total = 0;
    for(var i=0; i<this.dataStore.length; ++i){
        total += this.dataStore[i];
    }
    return (total / this.dataStore.length).toFixed(2);
}

var weekTemp = new weekTemps();
weekTemp.addFunc(54);
weekTemp.addFunc(52);
weekTemp.addFunc(48);
weekTemp.addFunc(44);
weekTemp.addFunc(56);
weekTemp.addFunc(51);
weekTemp.addFunc(47);
console.log(weekTemp.averageFunc());


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: