将生成的0移动到数组的开头

时间:2019-05-27 22:14:35

标签: javascript arrays sorting

我想将所有种子[i]值放在右边,导致零位留在左边。 但是,如果种子[i] = 0,我希望该0在右边。例如,值1056是可能的,因为如果我选择seed [i]为0。

// Download Function
function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
function genBatch (seed) {
    let result = new Array(4);
    for (var i = 0; i < 4; i++) {
        result[i] = seed[i] || "0";
    }
    return result.join("");
}

// Generate File
document.getElementById("generate").addEventListener("click", function(){   
   
    let batch = document.getElementById("batchNumber").value;
    /* /header2 */ 
    let text =  genBatch(batch) + "  ";

    let fileName = document.getElementById("fileName").value + ".txt";
    
    download(fileName, text);
}, false);
<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="container">
          <label for="batchNumber" class="font-weight-bold">Batch Number:</label>
          <input id="batchNumber" type="number" maxlength="4" size="4"/>
          <label for="fileName" class="font-weight-bold">File Name:</label>
          <input id="fileName" type="text"/>
    </div>  
    <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
    <script src="js/app.js"></script>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

.toLocaleString()minimumIntegerDigits选项一起使用。

const padZ = (num, min) => num.toLocaleString('en-US',{
  minimumIntegerDigits:min,useGrouping:false
});

console.log(padZ(4,4))
console.log(padZ(40,4))
console.log(padZ(400,4))
console.log(padZ(4000,4))

答案 1 :(得分:1)

我认为您只是在寻找padStart方法。

String​.prototype​.pad​Start() MDN

const getAsString = (num, minLen) => {
  return (num||'').toString().padStart( minLen||4, '0'); 
};

console.log(getAsString());
console.log(getAsString(1));
console.log(getAsString(333));
console.log(getAsString(1234));