【问题标题】:javascript for loop & functionjavascript for 循环和函数
【发布时间】:2016-02-05 03:13:27
【问题描述】:

我正在尝试使用一个按钮创建一个页面,该按钮在单击时调用一个函数以使用 for 循环。需要循环代码 5 次,并返回一个如下所示的页面:

$
$$
$$$
$$
$

我很难理解它,很少有例子不仅仅关注整数。她在我所在的地方……

<html>
<head>
  <button onclick="myFunction()">Click This Button</button>


</head>

<body>
  <p id="dollar"></p>

  <script type = "javascript/text">
    function myFunction() {
    var a;
    if(a===0) || (a===4) {
        document.write("$" + <br />);
    }
    if(a===1) || (a===3) {
        document.write("$$" + <br />);
    }   
    if (a===3) {
        document.write ("$$$" + <br />);
    }
    for (a = 0; a < 5; a++){

    }

    document.getElementById("dollar").innerHTML = text;

    }

  </script>


</body>
</html>

【问题讨论】:

  • 对于初学者&lt;button&gt; 不能在头脑中。 Next..如果在加载页面后使用document.write,将清除整个页面
  • 我不确定为什么这个问题被否决了。对 OP 试图实现的目标有一个明确的声明,并且 OP 正在展示他们迄今为止的工作并寻求帮助。这对我来说似乎很好。
  • a===2的时候呢?
  • 不要使用document.write,把&lt;button&gt;从你的脑海中抹去。
  • @j08691 "把你的按钮从你的脑袋里拿出来" :)

标签: javascript function for-loop


【解决方案1】:

你的可操作的东西在你的循环之外。

    function thisThing(){
        var finalIs =""
        for (a = 0; a < 5; a++){    
            if((a==0) || (a==4)) {
              finalIs += "$<br />";
           }
          if (a==3) {
                finalIs += "$$$<br />";
            }
          if((a==1) || (a==3)) {
                finalIs += "$$<br />";
            }   


        }
document.getElementById("dollar").innerHTML = finalIs;
        }

此外,您无需声明“a”,因为您在开始循环时已声明它。 此外,您的文档写入语句不正确。您将它们设置为好像 &lt;br /&gt; 是一个变量。它不是。这只是字符串的其余部分。

编辑:这个最终版本完美运行。已修复所有错误。 您可以自己查看差异。

【讨论】:

  • text 在这里仍未声明,也没有解决a===2 时应该发生的情况。
  • 仍然会失败,因为每个write 都会清除之前的write,并且在一个write 之后该元素也不存在
  • 这是真的。我修好了。
【解决方案2】:

将此代码用于任何数字 5 或 7 或 9 或....

  function myFunction(cnt) {
    var text = '';
    for (var i = 0; i < cnt; i++){
        if(i<(cnt/2)){
            for (var j = 0;  j< (i+1); j++){
                text+= "$";
            }
            text+= '<br />';
        }
        else{
            for (var j = 0;  j< (cnt-i); j++){
                text+= "$";
            }
            text+= '<br />';
        }
    }
    document.getElementById("dollar").innerHTML = text;
}

例如:

    myFunction(11);

结果:

$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$

示例

    function callmyFunction(){
        var tmp=document.getElementById("countDollar").value;
        myFunction(+tmp);
    }
    function myFunction(cnt) {
        var text = '';
        for (var i = 0; i < cnt; i++){
            if(i<(cnt/2)){
                for (var j = 0;  j< (i+1); j++){
                    text+= "$";
                }
                text+= '<br />';
            }
            else{
                for (var j = 0;  j< (cnt-i); j++){
                    text+= "$";
                }
                text+= '<br />';
            }
        }
        document.getElementById("dollar").innerHTML = text;
    }
<input id="countDollar" value="15" />
<button onclick="callmyFunction()" >Click me!</button>

<div id='dollar'>

【讨论】:

    【解决方案3】:

    例如,使用值数组:

    var patterns = ['$', '$$', '$$$', '$$', '$'];
    function myFunction() {
        var text = '';
        for (var i = 0; i < patterns.length; i++)
          text+= patterns[i] + '<br />';
    
        document.getElementById("dollar").innerHTML = text;
    }
    

    注意:去掉循环也可以达到同样的效果:

    var patterns = ['$', '$$', '$$$', '$$', '$'];
    function myFunction() {
        document.getElementById("dollar").innerHTML = patterns.join('<br />') + '<br />';
    }
    

    注意:只是玩...

    var waiter = function (selector, framerate, patterns) {
      var element = document.querySelectorAll(selector)[0];
      
      element.style.css = "display: none";
      
      var timer, frame;
      
      return {
        tick: function () {
            element.innerHTML = '[' + patterns[frame].replace(/\s/g, '&nbsp;') + ']';
            frame = ++frame % patterns.length;
        },
    
        show: function () {
          frame = 0;
          if (timer)
            window.clearInterval(timer);
          
          timer = window.setInterval(function () {
            this.tick();
          }.bind(this), framerate);
          
          element.style.css = "display: block";
        },
      }
    };
    
    waiter('#waiter', 50, [
        '> -------',
        '>> ------',
        ' >> -----',
        '- >> ----',
        '-- >> ---',
        '--- >> --',
        '---- >> -',
        '----- >> ',
        '------ >>',
        '------- >',
        '------- <',
        '------ <<',
        '----- << ',
        '---- << -',
        '--- << --',
        '-- << ---',
        '- << ----',
        ' << -----',
        '<< ------',
        '< -------',
      ]).show();
    
    waiter('#waiter2', 50, [
        '> -------',
        '>> ------',
        ' >> -----',
        '- >> ----',
        '-# >> ---',
        '-#- >> --',
        '-#-# >> -',
        '-#-#- >> ',
        '-#-#-# >>',
        '-#-#-#- >',
        '-#-#-#- <',
        '-#-#-# <<',
        '-#-#- << ',
        '-#-# << -',
        '-#- << #-',
        '-# << -#-',
        '- << #-#-',
        ' << -#-#-',
        '<< #-#-#-',
        '< -#-#-#-',
        '> -#-#-#-',
        '>> #-#-#-',
        ' >> -#-#-',
        '- >> #-#-',
        '-- >> -#-',
        '--- >> #-',
        '---- >> -',
        '----- >> ',
        '------ >>',
        '------- >',
        '------- <',
        '------ <<',
        '----- << ',
        '---- << -',
        '--- << --',
        '-- << ---',
        '- << ----',
        ' << -----',
        '<< ------',
        '< -------',
      ]).show();
    
    waiter('#waiter3', 100, [
        '>        ',
        '>>       ',
        ' >>      ',
        '- >>     ',
        '-- >>    ',
        '--- >>   ',
        '---- >>  ',
        '----- >> ',
        '------ >>',
        '------- >',
        '-------- ',
        '---------',
        '<--------',
        ' <-------',
        '( =------',
        ' ( =-----',
        '  ( <----',
        '   ( <---',
        '    ( =--',
        '     ( =-',
        '      ( <',
        '       ( ',
        '        (',
        '         ',
      ]).show();
      
    if (!String.prototype.x) {
      String.prototype.x = function (times) {
        return Array(times + 1).join(this);
      }
    }
      
      
    var blink =
        '  -___-  |'.x(4) +
        '  -___o  |' +
        '  -___O  |'.x(4) +
        '  -___o  |' +
        '  -___-  |' +
        '  o___o\' |' +
       ('  O___O" |'.x(2) +
        '  -___-" |').x(2) +
        '  O___O" |'.x(10) +
        '  -___-" |' +
        '  O___O  |'.x(10) +
        '  o___o  |'.x(10) +
        '  -___-  |'.x(10) +
        '  -___o  |'.x(16) +
        '  -___-  |'.x(10);
    
    waiter('#waiter4', 100, blink.replace(/^\||\|$/, '').split('|')).show();
    .waiter {
      font-family: Consolas, Courier;  
    }
    <div class="waiter" id="waiter"></div>
    <div class="waiter" id="waiter2"></div>
    <div class="waiter" id="waiter3"></div>
    <div class="waiter" id="waiter4"></div>

    【讨论】:

      【解决方案4】:

      此代码按照您想要的方式工作。但是,它不推荐。当您将按钮放在头上时,您的 html 代码不正确,并且当您放置 () 时,您的 javascript 条件不正确。希望这会有所帮助...

      <head>
          <script>
              function myFunction() {
      
              var a;
              for(a=0; a<5; a++){
      
              if(a===0 || a===4) {
              document.write("$<br/>");
              }
              if(a===1 || a===3) {
              document.write("$$<br>");
              }   
              if (a===2) {
              document.write ("$$$<br/>");
              }
              }
              }
          </script>
      </head>
      
      <body>
          <button type="button" onclick="myFunction()">Click This Button</button>
      
      </body>
      

      【讨论】:

        【解决方案5】:

        这是一个使用单个循环、一个临时变量和一个数组的简单方法:

         function myFunction() {
           for (var a = 1; a <= 5; a++) {
             x = a;
             if (x > 3) x = 6 - a;
             document.getElementById("dollar").innerHTML += Array(x + 1).join("$") + '<br />';
           }
         }
        <button onclick="myFunction()">Click This Button</button>
        <p id="dollar"></p>

        【讨论】:

        • 我想知道,哪个部分更简单,这个:x = a; if (x &gt; 3) x = 6 - a;,或者这个:Array(x + 1).join("$")。从初学者的角度来看,我的意思是......
        【解决方案6】:

        这是使用上述解决方案的固定版本。 然而,ankhzet 的回答是一个更干净的方法。

        <html>
        <head>
          <!-- script in head -->
          <script type = "javascript/text">
            function myFunction() {
              var a;
              var text = "";
        
              for ( a = 0; a < 5; a++ ){
                // if statements within the loop
                if( a === 0 || a === 4 ) { // All conditionals must be within one set of parenthesis. You can have others within, but all must be contained in one.
                  text += "$<br />";
                }
                if( a === 1 || a === 3 ) {
                  text += "$$<br />";
                }   
                if ( a === 2 ) {
                  text += "$$$<br />";
                }
              }
              document.getElementById( "dollar" ).innerHTML = text;
            }
          </script>
        </head>
        <body>
          <!-- button in body -->
          <button onclick="myFunction()">Click This Button</button>
          <p id="dollar"></p>
        </body>
        </html>
        

        【讨论】:

          猜你喜欢
          • 2018-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-14
          • 2015-04-08
          • 2014-07-09
          相关资源
          最近更新 更多