简体   繁体   中英

javascript printing array into paragraphs

I am trying to make a local html to display some text from txt file (also local). I used this to read file into array and print it:

<input type="file" name="files" id="inputfile">
<script type="text/javascript"> 
document.getElementById('inputfile')
.addEventListener('change', function() {
    var test=new FileReader();
    test.onload=function(){
        document.getElementById('output')
                .textContent=fl.result;
    }
    test.readAsText(this.files[0]);
})
</script>

However, I would like to print it from the array into paragraphs, line by line (first line goes into heading, second into paragraph, third into heading and so on...). Is there a way to do it automaticaly from an array, or would I have to do it by hand for each one? I am kinda green in javascript so I would rather refrain from using node etc.

If the headers and paragraphs are always strictly alternating, you can check whether each array index is odd or even to decide whether to wrap it in header or paragraph tags. One way:

 arr = ["header", "paragraph", "header", "paragraph", "header", "paragraph"] joined = arr.map((el, i) => { return (i % 2 === 0) ? `<h1>${el}</h1>` : `<p>${el}</p>` ; }).join('') console.log(joined)

 const arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3']; const result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join(''); document.getElementById('output').innerHTML = result ;
 <div id="output"></div>

Put this in your code:

function arrToPar(arr){ //For JS-Array --> HTML content
    var out = "";
    for(var i = 0; i < arr.length; i++){
        out += arr[i] + "<br>";
    }
    return(out);
}

Or...

function arrToString(arr,joiner = " "){ //For JS-Array --> JS-String
    var out = ""; //The parameter "joiner", by default, is a space
    //This means that you only need to specify "arr", but you can do
    //a second parameter. This function behaves like arr.join(joiner).
    for(var i = 0; i < arr.length; i++){
        out += arr[i] + joiner;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM