Understanding Substr

182 views Asked by At

I have a block of javascript here. Simple script that does as it is supposed to here:

var char, num, i, line, j;

 char = input[0];
 num = input[1];
 l = "";
 var Lines = new Array();

 for ( i=0; i <= num; i++ ) {
       l = l+char+char+char;
             for ( j=0; j <= num; j++ ) {
                   Lines[i] = l.substr(0, 1*i);
        }
           print(i +" " + Lines[i]);
    }

My issue is I do not understand this line: Lines[i] = l.substr(0, 1*i);

I am trying to learn here okay and this is one of the few sites I see that have been helpful so please refrain from assinine remarks. This is not homework. It is me trying to make sense of things since the teacher's way of teaching is not helping with my understanding. In fact the whole class is having an issue.

the desired output is to simply print a character over and over a given number of times while creating a new line so if say M is entered (char) and 6 is entered as the input (num)... the 1st line prints one M the 2nd line prints 2 Ms, 3rd three Ms, and so forth for the given number of times, in this case is 6 making 6 lines and 6 Ms (right triangle I guess you can say. This way can be used to make a diamond too.)

I just do not get where "*i" comes into it. I know substr(0,1) is just the 1st character. I do not see how the current number i is affects the substr result.

Explanation: char is the character entered, num is the number entered. In class we use an HTML file to run the javascript where the print statement is used instead of say document.write and having to save .js files. The teacher does not even get into all that stuff. In case you are wondering the class is Programming Logic 105. I haven't looked at programming since high school during the PASCAL, BASIC and C days. I am not used to the dynamic nature of Javascript. I guess the school deems Javascript as a good open door into programming.

2

There are 2 answers

2
Anubhav On

Using this Lines[i] = l.substr(0, 1+i); instead might do the trick.

0
Chirag On

You have three options in Javascript:

//slice
//syntax: string.slice(start [, stop])
"Good news, everyone!".slice(5,9); // extracts 'news'

//substring 
//syntax: string.substring(start [, stop])
"Good news, everyone!".substring(5,9); // extracts 'news'

//substr
//syntax: string.substr(start [, length])
"Good news, everyone!".substr(5,4); // extracts 'news'