【问题标题】:How to combine var? + Example script如何结合var? + 示例脚本
【发布时间】:2018-07-26 11:39:15
【问题描述】:

按第一个按钮,我应该有一些随机数,

817
754
692

按下第二个按钮“123:123”,数字应如下所示:

817:817
754:754

但我得到的是:

817
754
:817
754

请问如何组合它们?

function ra(length) {
  var consonants = "123456789",
    vowels = '123456789',
    rand = function(limit) {
      return Math.floor(Math.random() * limit);
    },
    i, word = '',
    length = parseInt(length, 10),
    consonants = consonants.split(''),
    vowels = vowels.split('');
  for (i = 0; i < length / 2; i++) {
    var randConsonant = consonants[rand(consonants.length)],
      randVowel = vowels[rand(vowels.length)];
    word += (i === 0) ? randConsonant.toLowerCase() : randConsonant;
    word += i * 2 < length - 1 ? randVowel : '';
  }
  return word;
}
$("#click").click(function() {
  $("#test").text('');
  for (var p = 0; p < 5; p++) {
    var pass1 = ra;
    $("#test").append(pass1(3) + '\n');
  }
});

$("#combine").click(function() {
  var userpass = document.getElementById('test').value;
  $("#test").append("" + userpass + ":" + userpass + "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
<textarea id="test" rows="5"></textarea>
<button id="combine">123:123</button>

http://jsfiddle.net/t0deq5zu/1/

【问题讨论】:

  • jsfiddle 中有一个很好的提示,整洁的按钮会格式化你的代码

标签: jquery


【解决方案1】:

您需要拆分并循环遍历每一行 - 目前您将所有值作为一个变量。请参阅下面的合并单击事件中的编辑(代码中的 cmets)

function ra(length) {
  var consonants = "123456789",
    vowels = '123456789',
    rand = function(limit) {
      return Math.floor(Math.random() * limit);
    },
    i, word = '',
    length = parseInt(length, 10),
    consonants = consonants.split(''),
    vowels = vowels.split('');
  for (i = 0; i < length / 2; i++) {
    var randConsonant = consonants[rand(consonants.length)],
      randVowel = vowels[rand(vowels.length)];
    word += (i === 0) ? randConsonant.toLowerCase() : randConsonant;
    word += i * 2 < length - 1 ? randVowel : '';
  }
  return word;
}
$("#click").click(function() {
  $("#test").text('');
  for (var p = 0; p < 5; p++) {
    var pass1 = ra;
    $("#test").append(pass1(3) + '\n');
  }
});

$("#combine").click(function() {
  var userpass = document.getElementById('test').value;
  var lines = userpass.split('\n');  // split the values into each line
  
  if (lines.length) {
    $("#test").empty();             // empty the textarea
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].trim() != '') {   // don't append empty line
          if (lines[0].indexOf(':') > -1) {  // button already pressed so re-append same
            $("#test").append(lines[i] + "\n")
          } else {
            $("#test").append(lines[i] + ":" + lines[i] + "\n");   // apend the new values
          }
        }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
<textarea id="test" rows="5"></textarea>
<button id="combine">123:123</button>

【讨论】:

    【解决方案2】:

    您正在处理$("#test"),它将所有数字一起作为其内容,因此所有数字一起被解耦。您需要单独解耦每一行(使用split('\n'))。

    working JSFiddle

    【讨论】:

    • 非常感谢程序员!
    【解决方案3】:

    我知道您已经有了答案,但我想详细说明一下您的代码中的一些 cmets,希望能帮助您编写更清晰、更好的代码(+ 来自 ECMAScript6 的一些新内容)。 我会推荐两件主要的事情 - 始终缩进您的代码并在其中添加一些 cmets。

    所以这里是一些 cmets 的代码:

    // always use better names of your functions (names that would be like a hint what is the purpose of that function)
    function ra (length) {
        // all the variables that won't change during your function should be declared as constansts
      const consonants = "123456789".split('');
      const vowels = '123456789'.split('');
      const consonantLength = consonants.length;
      const vowelsLength = vowels.length;
    
      let rand = function(limit){
        return Math.floor(Math.random()*limit);
      }
      // no need to declar i here when you can do so in the for loop
      //-- var i = '';
    
      // not sure why would you use this radix (the second argument of parseInt)
      length = parseInt(length,10);
    
      // there is no need to perform the split() on a separate row as this can be done with the initial declaration of your 
      //-- consonants = consonants.split('');
      //-- vowels = vowels.split('');
    
        let word = '';
      let loopLength =  length/2; // check this for more explanations https://stackoverflow.com/questions/8452317/do-loops-check-the-array-length-every-time-when-comparing-i-against-array-length
      for (let i = 0; i < loopLength; i++) {
    
        // in your code you where using consonants.length which will be executed each time so instead of this I will use the constant consonantLength that I have declared above
            let randConsonant = consonants[rand(consonantLength)];
        let randVowel = vowels[rand(vowelsLength)];
        // not sure what are you doing here, so can't comment much. It is a very good practice to leave some comments on places where the main logic of your code is happening
        word += (i === 0) ? randConsonant.toLowerCase() : randConsonant;
        word += i*2 < length-1 ? randVowel : '';
      }
    
      return word;
     }
    
     // the jQuery event 'click' is a bit old and will get some day deprecated, instead I would suggest to use 'on' 
     $("#click").on('click',function(){
      $("#test").text('');
      //-- var pass1 = ra; // there is no need of this row. you can just call the function ra down below in the loop
      for(var p = 0; p < 5; p++){
        $("#test").append(ra(3)+'\n');
        }
    });
    
    $("#combine").on('click',function(){
      // let's get the value from the textarea, and as it will be a string we need to split it by rows
      // btw: I believe there is a better regex that will exclude the last \n 
      let userpass = document.getElementById('test').value.split(/\n/g);
      // and we remove the last element from the array that will be an empty one
      userpass.pop();
      // we loop through all the elements from the array 
        for (let row of userpass) {
        // we do check if there is value in row as the last element will be an empty string
        $("#test").append(row+":"+row+'\n');
      }
    });
    

    还有一个JSFiddle

    【讨论】:

    • 谢谢,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-02-11
    • 2021-08-11
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 2016-01-02
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多