var global_num = 12          // glocal var
class Numbers {
   num_val = 13;             // instance var
   static sval = 10;         // static var
   
   storeNum():void {
      var local_num = 14;    // local var
   }
};
console.log("glocal var is: " + global_num);
console.log("static var is :" + Numbers.sval);
var obj = new Numbers();
console.log("instance var: " + obj.num_val);

Output:

➜  type git:(main) ✗ node index.js
glocal var is: 12
static var is :10
instance var: 13

Here are two same variable declaration in the nested for loop. But the second var i will overlay rewriting the first one.So the sum contains only the first row values in the following example. 

function sumMatrix(matrix: number[][]) {
    var sum = 0;
    for (var i = 0; i < matrix.length; i++) {
        var currentRow = matrix[i];
        for (var i = 0; i < currentRow.length;i++) {
            sum += currentRow[i];
        }
    }
    return sum;
}

let matrix:number[][] = [[2, 0], [0, -1]]
console.log( sumMatrix( matrix ) );  //output 2

We can use let instead of var for i when declare them in the nested for loop to fix the bug.
Because the variable declared by let has the local scope.

function sumMatrix(matrix: number[][]) {
    var sum = 0;
    for (let i = 0; i < matrix.length; i++) {
        var currentRow = matrix[i];
        for (let i = 0; i < currentRow.length;i++) {
            sum += currentRow[i];
        }
    }
    return sum;
}


let matrix:number[][] = [[2, 0], [0, -1]]
console.log( sumMatrix( matrix ) );  //output 1
Categories: Web

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x