Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 34
  1. #1
    New to the CF scene
    Join Date
    Apr 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript: Writing a function to accept two integer parameters

    I am trying to write a JS function called 'count' which will accept two integer parameters and then return a string listing all of the numbers between the two parameters. For example, if I called count(0,10) then the program should display 0,1,2,3 etc and finally 10. However, after extensive trying, I have only succeeded in displaying the numbers with no spaces between them
    (012345678910). Any guideance would be appreciated.

    function count(num1, num2)
    {

    var strCou = '';

    for(count = num1; count <= num2; count++)
    {
    strCou += count;
    }

    console.log(strCou);
    }
    count(0,10);

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    You may not use the same name - count - for a function and a variable.


    Code:
    <script type = "text/javascript">
    
    function count(num1, num2) {
    var strCou = '';
    for (var i = num1; i <= num2; i++) {
    strCou += i + " ";
    }
    alert ((strCou));
    }
    count(0,10); 
    
    </script>

    It is recommended that you place the opening brace following the function, if, else, for, while, do, switch, and try statements on the same line and not on the following line. Apart from that every Javascript statement should be followed by a semi-colon (;). It is quite possible to disregard this advice, but if you do one day it will rise up and bite you in the undercarriage.




    Quizmaster: What creatues live in a formicary?
    Contestant: Owls.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by dteece1 View Post
    I am trying to write a JS function called 'count' which will accept two integer parameters and then return a string listing all of the numbers between the two parameters.
    i hate loops, string concats, and vars, so here's how i would do it:
    Code:
    function count(num1, num2) {
      return Object.keys(new String(Array(num2+2))).slice(num1).join(" ");
    }
    
    //test:
    alert(
      count(0,10)
    );
    Last edited by rnd me; 04-11-2013 at 07:09 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by rnd me View Post
    i hate loops, string concats, and vars, so here's how i would do it:
    Code:
    function count(num1, num2) {
      return Object.keys(new String(Array(num2+2))).slice(num1).join(" ");
    }
    
    //test:
    alert(
      count(0,10)
    );

    There are of course several different ways to kill a cat. But I somehow doubt whether the OP (or his teacher) will find that comprehensible. And you ought to mention that the code will work only in HTML5 with a <!DOCTYPE> declaration.
    Last edited by Philip M; 04-11-2013 at 07:28 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by Philip M View Post
    And you ought to mention that the code will work only in HTML5 with a <!DOCTYPE> declaration.
    please explain what you mean there, it should be fine in xhtml and html4 afaik...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    And you ought to mention that the code will work only in HTML5 with a <!DOCTYPE> declaration.
    JavaScript doesn't care what version of HTML you are using - all that matters is whether the browser supports the version of JavaScript.

    In this instance all browsers that run JavaScript support that command so only browsers that run JScript instead (such as IE8) would have problems with it. As only a few lines of code are needed to implement support for the command for antiquated browsers it is perfectly appropriate to use now.

    It certainly is the way that such processing in JavaScript ought to be being taught since that's the way those learning JavaScript now will be expected to write such calls in the future.

    The problem is that most people teaching JavaScript teach how to write it assuming Netscape 4 and similar will be the browser everyone uses whereas they should be teaching for Internet Explorer 11 and similar.
    Last edited by felgall; 04-11-2013 at 08:28 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by rnd me View Post
    please explain what you mean there, it should be fine in xhtml and html4 afaik...
    Using IE9 it will not work for me without a !DOCTYPE declaration.

    It does indeed work in Chrome.

    Lots of people are still using IE8. It is silly to pretend that everyone has the latest browser installed.

    @felgall. I see no reason why a complicated technique should be used in any situatiion when a simple one will do the job just fine. As they say - "Never use 10 words when 50 will do". Advanced codes should be reserved for situations which actually require them. I still doubt doubt whether the OP (or his teacher) will find rnd me's code comprehensible. What is for sure, the OP cannot hand that in and successfully pretend it is his own work.
    Last edited by Philip M; 04-12-2013 at 10:19 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    Banned
    Join Date
    Mar 2013
    Posts
    139
    Thanks
    0
    Thanked 9 Times in 9 Posts
    Quote Originally Posted by dteece1 View Post
    I have only succeeded in displaying the numbers with no spaces between them
    (012345678910). Any guideance would be appreciated.
    This is obviously a homework exercise.

    When we were given the same homework, we got extra marks if you didn't have a redundant space after the last integer. There's lots of ways to not have a redundant space, here is one:

    Code:
    <script type="text/javascript">
                var num1=0, num2=10;
                function getNumsBetween(num1,num2){
                    var strOut=''
                    for(var i=num1; i <= num2; i++){
                        strOut += i + ((i < num2)? ',' : '');
                    }
                    return strOut;
                }
                alert(getNumsBetween(num1,num2));
            </script>
    I've used a comma instead of space though.

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    Using IE9 it will not work for me without a !DOCTYPE declaration.
    You shouldn't be writiing web pages without a doctype - if you do then you lose control of how they will look in duifferent browsers.

    rnd_me's solution will work fine in IE4 provided that you include some code to add the missing Object.keys methods for obsolete browsers that didn't support it.

    there are lots of JavaScript commands that antiquated browsers didn't support but which can be added easily with a small piece of code.

    If the teacher can't understand the single line of code using Object.keys then perhaps they ought to take a JavaScript course and learn JavaScript - that call is fairly basic to the way that modern JavaScript works since it distinguishes between properties attached directly from those that are inherited.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by Philip M View Post
    I see no reason why a complicated technique should be used in any situatiion when a simple one will do the job just fine. As they say - "Never use 10 words when 50 will do". Advanced codes should be reserved for situations which actually require them.
    actually mine is shorter and simpler, maybe even faster.

    are you saying never use native methods when user-land loops and vars will do? that's silly and everyone knows it.


    just because it doesn't read like procedural BASIC doesn't make it complicated or advanced. to me, loops and private vars are complex.
    after all, noobs often forget a "var " and create inadvertent globals. loops can be coded wrong and loop forever, crashing the tab!


    even cut and pasting your code, if i inadvertently pass -1 as num2 to your function, guess what happens? badness that won't happen when using native methods only...


    in short, there are more keywords and far more moving pieces in your solution and thus more places to mess things up.


    i think it's a matter pf perspective:
    if one learns JS like it's still 1987, then a functional programming is more complex to them.
    if one learns how to use what's already there, doing it yourself seems complicated.
    Last edited by rnd me; 04-12-2013 at 09:38 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by rnd me View Post
    even cut and pasting your code, if i inadvertently pass -1 as num2 to your function, guess what happens? badness that won't happen when using native methods only...
    And if I inadvertently pass -10 to your code as num2, guess what happens?

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    And if I inadvertently pass -10 to your code as num2, guess what happens?
    No need to guess - defining an array having a negative number of entries results in an array containing no entries whatsoever.

    The code ought to test that both numbers are positive integers with the second number not being smaller than the first. Both variants of the code are missing that error checking code.

    So a practical version would be:

    Code:
    getNumsBetween = function(a, b) {
      if (a !== Math.floor(+a) || b !== Math.floor(+b)) throw new TypeError();
      if (a < 0 || b < a) throw new RangeError();
      return Object.keys(new String(Array(b+2))).slice(a).join(' ');
    }
    
    alert(getNumsBetween(6,10)); // '6 7 8 9 10'
    alert(getNumsBetween(7,-10)); // range error
    alert(getNumsBetween('a',27)); // type error
    Last edited by felgall; 04-13-2013 at 08:27 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by felgall View Post
    The code ought to test that both numbers are positive integers with the second number not being smaller than the first. Both variants of the code are missing that error checking code.
    So if the student prefers something more basic (but equally effective) that he might conceivably persuade his teacher is (more or less) his own work:-

    Code:
    <!DOCTYPE>
    <html>
    <head>
    
    <script type = "text/javascript">
    
    function count(num1, num2) {
    
    if ( (isNaN(num1)) || (isNaN(num2)) || (num1 <0) || (num2 <= num1)  ) {
    alert ("Invalid parameters!")
    return false;
    }
    
    var strCou = '';
    for (var i = num1; i <= num2; i++) {
    strCou += i + " ";
    }
    strCou = strCou.replace(/\s$/,"");  //delete final space
    alert ((strCou));
    }
    
    count(0,10); 
    
    </script>
    </body>
    
    </html>
    I don't disagree that your code is more modern and in many ways to be preferred (or would be if it worked in IE8 which is still widely used), although IMO what matters most is whether it works reliably in all currently-used browsers, not how elegent/sophisticated it is. Where we do not agree is what is appropriate code to offer to students who are obviously raw beginners. Medical students are not expected to do heart or brain surgery before they have leaned how do treat ingrowing toenails.

    As an aside, I did badly at chemistry and physics at school as our teachers, although holding Doctor's degrees, and being the authors of many learned papers and the standard textbooks, had no clue how to teach students properly. Perhaps they were bored by schoolchildren and yearned for more rarified groves of academia in which to profess their undoubted but impenetrable knowledege. The teacher from whom I learned the most and with the most enthusiasm (and respect) was in fact unqualified and not even a graduate - he had been taken on in the war years. He may only have been a few pages ahead of his students in the textbook, but he certainly knew how to motivate boys towards his subject! That included avoiding the discouragement (leading to dislike of the subject) which came from making them run before they could walk. Or raising nit-picking and academic criticisms of their homework, so the student was always wrong - and soon became demotivated.

    It is quite wrong to suppose that someone who is highly knowledgable and competent in his subject can ipso facto teach it.

    Mecahnistic situations call for mechanistic techniques - to diagnose what is wrong with something (such as a computer program), and put it right. But human beings are organisms, not mechanisms, so the correct approach in teaching is to identify what is being done right, and then cultivate or build on it.
    Last edited by Philip M; 04-13-2013 at 12:08 PM. Reason: Typo

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    AndrewGSW (04-13-2013)

  • #14
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    @Philip Your DOCTYPE declaration is incomplete, as are your head and body-tags.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by AndrewGSW View Post
    @Philip Your DOCTYPE declaration is incomplete, as are your head and body-tags.
    Oh sorry! Mea culpa!

    What is wrong with the <!DOCTYPE>?

    Or do you mean to prefer

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    Last edited by Philip M; 04-13-2013 at 03:06 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  
    Page 1 of 3 123 LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •