简体   繁体   English

javascript将数组打印成段落

[英]javascript printing array into paragraphs

I am trying to make a local html to display some text from txt file (also local).我正在尝试制作一个本地 html 来显示 txt 文件(也是本地)中的一些文本。 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.我在 javascript 方面有点绿色,所以我宁愿避免使用节点等。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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