【问题标题】:Add array values without clearing previous value using javascript使用javascript添加数组值而不清除先前的值
【发布时间】:2016-09-09 00:47:17
【问题描述】:

我有一个可以正常工作的密码生成器。但需要一点改变。下图显示

单击“生成密码”按钮后,它会生成一个密码。 必填:当我再次单击该按钮时,我需要在下面生成另一个密码而不清除之前的密码。尝试了几种循环变体,但都不起作用。

**passGen.js**

function passGen() {
var Generator = {};
Generator.generateMnemonic = function(length, num_length, mixcase) {
var ret = '';
var vowels = 'aeioe';
var consonants = 'bcdfghklmnpqrstvwxzy';
if (mixcase) {
    vowels += vowels.toUpperCase();
    consonants += consonants.toUpperCase();
}
vowels = vowels.split('');
consonants = consonants.split('');

for(var i = 0; i < length / 2; i++) {
    ret += vowels.getRandom();
    ret += consonants.getRandom();
}

if (!num_length) return ret;

var pos = $random(2, length - 2 - num_length);
return ret.substr(0, pos) + $random(Math.pow(10, num_length - 1),    Math.pow(10, num_length) - 1) + ret.substr(pos + num_length);
    };
    var observe = new Observer('#generator-length, #generator-num_length,  #generator-mixcase, #generator-amount', function(values) {
    var length = values[0].toInt();
    var num_length = values[1].toInt();
    var mixcase = values[2].toInt();
    var amount = values[3].toInt();

    // Fill passwords in a loop
    var words = [];
    for (var i = 0; i < amount; i++) {
        words.push(Generator.generateMnemonic(length, num_length, mixcase)   );

    }

    // Get the output area
    var output = $('generator-output');

    // Output it and highlight it so users will notice the update
    output.value = words.join("\n");
    output.getParent().highlight('#ff8', '#fff');


   }, {
   //   periodical: 1000 // interval in ms
   });

   // To fill in the first values
   observe.fire();
   }
   **Part of Hmtl**
 <script type="text/javascript" src="passGen.js"></script> 
<span>How many passwords:</span>
    <br>
    <select name="amount" id="generator-amount">
        <option value="1" selected>1</option>
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="50">50</option>
        <option value="100">100</option>
    </select>
</label>
<input type="button" name="button" value="Generate Password" onclick="passGen();">
<label>
<br>
    <span>Your passwords:</span>


【问题讨论】:

  • 能否请您发布一个现场示例?
  • 你可以为它创建一个 jsfiddle 吗?

标签: javascript html arrays push


【解决方案1】:

按照这些思路做一些事情:(给人感觉的小例子)使用静态变量。

function passGen() {
 if ( typeof passGen.words == 'undefined' ) { /* It has not been called do initialization*/
 passGen.words = [];}//else previous passwords persist, and you push, onto them.
 passGen.words.push("Hello");
 alert(passGen.words);
}
passGen();
passGen();

在你的情况下,保留我的初始如果,删除你的行

var words = [];

并添加 passGen。到你的 words.push 和 words.join

改编自Static variables in JavaScript

【讨论】:

    猜你喜欢
    • 2017-12-18
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多