最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript multiple loops - Stack Overflow

programmeradmin2浏览0评论

I am trying to get the sum of a list of words displayed in an HTML browser.

If each word is assigned a number i.e

a is 1, b is 2

and so on upto z is 26, then the sum of apple should be 50. I want them to be displayed in browser like below:

apple  
carrot
money  

50
75
72

but I am not able to get the loop to work correctly.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
   function newSquare(){
      for(var j=0; j<10; j++){
         calcAlpha(j);
      }
   }
   function newDisplay(){
      for(var k=0; k<10; k++){
         calcAlpha(k);
      }
   }
   function calcAlpha() {
      var word = document.getElementById("square + j").childNodes[0].data;
      var sum = 0;
      for(var i=word.length-1; i>=0; i--) {
         sum += (word.charCodeAt(i) - 96);
      }
      document.getElementById("display + k").innerHTML=sum
   }
</script>
</head>
<body>
   <h1>Calculate sum of words</h1>
   <table>
      <tr><td id="square1">apple</td></tr>
      <tr><td id="square2">carrot</td></tr>
      <tr><td id="square3">money</td></tr>
      <tr><td id="square4">game</td></tr>
   </table>
   <table>
      <tr><td id="display1">&nbsp;</td></tr>
      <tr><td id="display2">&nbsp;</td></tr>
      <tr><td id="display3">&nbsp;</td></tr>
      <tr><td id="display4">&nbsp;</td></tr>
   </table>
   <div id="display"></div>
   <button onclick="calcAlpha()">calculate</button>
</body>
</html>

Can someone can sort this for me? I am still a beginner at Javascript, and I dont understand how to put i,j, and k in loops. Thanks.

I am trying to get the sum of a list of words displayed in an HTML browser.

If each word is assigned a number i.e

a is 1, b is 2

and so on upto z is 26, then the sum of apple should be 50. I want them to be displayed in browser like below:

apple  
carrot
money  

50
75
72

but I am not able to get the loop to work correctly.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
   function newSquare(){
      for(var j=0; j<10; j++){
         calcAlpha(j);
      }
   }
   function newDisplay(){
      for(var k=0; k<10; k++){
         calcAlpha(k);
      }
   }
   function calcAlpha() {
      var word = document.getElementById("square + j").childNodes[0].data;
      var sum = 0;
      for(var i=word.length-1; i>=0; i--) {
         sum += (word.charCodeAt(i) - 96);
      }
      document.getElementById("display + k").innerHTML=sum
   }
</script>
</head>
<body>
   <h1>Calculate sum of words</h1>
   <table>
      <tr><td id="square1">apple</td></tr>
      <tr><td id="square2">carrot</td></tr>
      <tr><td id="square3">money</td></tr>
      <tr><td id="square4">game</td></tr>
   </table>
   <table>
      <tr><td id="display1">&nbsp;</td></tr>
      <tr><td id="display2">&nbsp;</td></tr>
      <tr><td id="display3">&nbsp;</td></tr>
      <tr><td id="display4">&nbsp;</td></tr>
   </table>
   <div id="display"></div>
   <button onclick="calcAlpha()">calculate</button>
</body>
</html>

Can someone can sort this for me? I am still a beginner at Javascript, and I dont understand how to put i,j, and k in loops. Thanks.

Share edited Aug 2, 2012 at 17:50 Bergi 667k161 gold badges1k silver badges1.5k bronze badges asked Aug 2, 2012 at 17:36 Sarah BossSarah Boss 412 silver badges5 bronze badges 2
  • 4 Your element ids should look like document.getElementById("display" + k).innerHTML=sum Close quotes and concatenate on the variable. – Michael Berkowski Commented Aug 2, 2012 at 17:46
  • Could you please elaborate about what these function should do, and what arguments they would have? Their names are not speaking, or don't match the code. – Bergi Commented Aug 2, 2012 at 17:52
Add a ment  | 

4 Answers 4

Reset to default 2

Here's a plete answer:

There are three main problems with the code. First, i, j, and k are var's with specific integer values in this example. "square + j" is just a string that does not have the desired values (i.e. square1, square2, etc.). As Michael has suggested, you should put "square" + j.

The second issue is that the only function to run in your webpage is calcAlpha(), which you call in the onclick event of the button element. Within calcaAlpha() you never call newSquare() or newDisplay(), so they never execute.

The third issue is the namespace, or scope of your javascript variables. Within calcAlpha() you cannot access the variables j or k because they are declared in external functions that don't encapsulate the calcAlpha() function. However, you can access the variable i because it is declared in calcAlpha().

The solution to your problem would be to remove newDisplay() and newSquare() and change calcAlpha() to something like this:

function calcAlpha() {
    for (var j = 1; j <= 4; j++) {
        var word = document.getElementById("square" + j).childNodes[0].data;
        var sum = 0;
        for(var i=word.length-1; i>=0; i--) {
            sum += (word.charCodeAt(i) - 96);
        }
        document.getElementById("display" + j).innerHTML=sum

    }
}

This is basically the bined code for newSquare() and newDisplay() which is put into calcAlpha() and fixed for the other issues described above. Notice that the variable k is unnecessary because you want to put the numeric sum of squareN into displayN, so you can use a single variable, j.

I'm not sure what you want to do with those functions, but try this:

function run() {
// reads, calculates and prints all words
    for (var i=1; i<=4; i++) {
        var word = document.getElementById("square"+i).childNodes[0].data;
        var result = calcAlpha(word);
        document.getElementById("display"+i).childNodes[0].data = result;
    }
}
function calcAlpha(text) {
   text = text.toLowerCase();
   var sum = 0;
   for (var i=text.length-1; i>=0; i--) {
       sum += text.charCodeAt(i) - 96;
   }
   return sum;
}

And call the run function from the button.

One thing I saw that you did incorrectly right away was getting the element by id. You were including the looping variable as a string instead of an int. Here is my solution:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">

   function calcAlpha()
   {
        for(j =1; j<=4; j++)
        {
            var word = document.getElementById("square" + j).innerHTML;
            var sum = 0;
            for(var i=word.length-1; i>=0; i--) 
            {
                sum += (word.charCodeAt(i) - 96);
            }
            document.getElementById("display" + j).innerHTML=sum
        }
   }

</script>
</head>
<body>
   <h1>Calculate sum of words</h1>
   <table>
      <tr><td id="square1">apple</td></tr>
      <tr><td id="square2">carrot</td></tr>
      <tr><td id="square3">money</td></tr>
      <tr><td id="square4">game</td></tr>
   </table>
   <table>
      <tr><td id="display1">&nbsp;</td></tr>
      <tr><td id="display2">&nbsp;</td></tr>
      <tr><td id="display3">&nbsp;</td></tr>
      <tr><td id="display4">&nbsp;</td></tr>
   </table>
   <div id="display"></div>
   <button onclick="calcAlpha()">calculate</button>
</body>
</html>

The first problem, like Michael said, is this:

document.getElementById("square + j")
// and
document.getElementById("display + k")

This will look for the element whose id exactly matches "square + j" or "display + k". To concatenate the value of a variable to a string, use "square" + j and "display" + k.

The second problem is that in the context of calcAlpha, the variables j and k are undefined. You can fix this by either making them accessible to calcAlpha (by defining them outside the scope of function calcAlpha) or by passing j (or k) as a parameter. You're already doing the first part of that (actually passing it along). All you need now is to use it in the declaration of calcAlpha, like so:

function calcAlpha(index) {
  var word = document.getElementById("square" + index).childNodes[0].data;
  // [...]
}

The variable index will now contain the value of the j or k you passed along.

One other thing: you're calling calcAlpha both from the other functions and from the <button>'s onclick. That's probably not what you want to do. Have a look at Bergi's answer, his/her solution should solve your problem.

发布评论

评论列表(0)

  1. 暂无评论