晴明的博客园 GitHub      CodePen      CodeWars     

[js] 处理二维数组

#

 1             //按列访问
 2             var grades = [
 3                 [89, 77, 78],
 4                 [76, 82, 81],
 5                 [91, 94, 89]
 6             ];
 7             var total = 0;
 8             var average = 0.0;
 9             for (var row = 0; row < grades.length; ++row) {
10                 for (var col = 0; col < grades[row].length; ++col) {
11                     total += grades[row][col]; //行不变,列变,可处理参差不齐的数组
12                 }
13                 average = total / grades[row].length;
14                 console.log("Student " + parseInt(row + 1) + " average: " +
15                     average.toFixed(2));
16                 total = 0;
17                 average = 0.0;
18             }
19             //按行访问
20             var grades = [
21                 [89, 77, 78],
22                 [76, 82, 81],
23                 [91, 94, 89]
24             ];
25             var total = 0;
26             var average = 0.0;
27             for (var col = 0; col < grades.length; ++col) {
28                 for (var row = 0; row < grades[col].length; ++row) {
29                     total += grades[row][col]; //行变,列不变
30                 }
31                 average = total / grades[col].length;
32                 console.log("Test " + parseInt(col + 1) + " average: " +
33                     average.toFixed(2));
34                 total = 0;
35                 average = 0.0;
36             }
37             //对象数组
38             function Point(x, y) {
39                 this.x = x;
40                 this.y = y;
41             }
42 
43             function displayPts(arr) {
44                 for (var i = 0; i < arr.length; ++i) {
45                     console.log(arr[i].x + ", " + arr[i].y);
46                 }
47             }
48             var p1 = new Point(1, 2);
49             var p2 = new Point(3, 5);
50             var p3 = new Point(2, 8);
51             var p4 = new Point(4, 4);
52             var points = [p1, p2, p3, p4];
53             for (var i = 0; i < points.length; ++i) {
54                 console.log("Point " + parseInt(i + 1) + ": " + points[i].x + ", " +
55                     points[i].y);
56             }
57             var p5 = new Point(12, -3);
58             console.log(p5); //Point {x: 12, y: -3}
59             points.push(p5);
60             displayPts(points);
61             points.shift();
62             displayPts(points);

 

posted @ 2016-02-24 01:23  晴明桑  阅读(1430)  评论(0编辑  收藏  举报