简体   繁体   English

Javascript中的字符串连接

[英]String concatenation in Javascript

Is there a way to concatenate strings and variable values and new lines, in javascript? 有没有办法在javascript中连接字符串和变量值以及换行符?

My code: 我的代码:

var variab = "Make:"+ make \n 
        "Model:" + model  \n 
        "Date taken: " + dateTime  \n 
        "File name:" + fileName ;
variab = variab.replace(/\n/g, '<br>');
        document.getElementById('exifid').innerHTML = variab;});

make, model, dateTime and fileName are all variables that return specific values, and I want them to be displayed into a list-like form in my div. make,model,dateTime和fileName都是返回特定值的变量,我希望它们在div中以列表形式显示。

You almost got it: 您几乎明白了:

var variab = "Make:" + make + "\n" +
    "Model:" + model + "\n" +
    "Date taken: " + dateTime + "\n" +
    "File name:" + fileName ;

variab = variab.replace(/\n/g, '<br>');
document.getElementById('exifid').innerHTML = variab;

You can also put each line in an Array and use .join("<br>") to save yourself some typing. 您也可以将每一行放入Array中,并使用.join("<br>")来节省输入时间。

Why use the replace? 为什么要使用替换?

var variab = "Make:"+ make + "<br>" +
"Model:" + model  + "<br>" +
"Date taken: " + dateTime  + "<br>" +
"File name:" + fileName ;
document.getElementById('exifid').innerHTML = variab;

For greater readability, I'd do this: 为了提高可读性,我会这样做:

var variab = [
    "Make:" + make,
    "Model:" + model, 
    "Date taken: " + dateTime,
    "File name:" + fileName
].join("<br />");

You're also free to include newlines within your fields this way. 您还可以通过这种方式在字段中自由添加换行符。

Unless your needs grow more complex. 除非您的需求变得更加复杂。 In that case, I'd use a templating framework. 在这种情况下,我将使用模板框架。

You could stuff each element into an array and then join them. 您可以将每个元素填充到数组中,然后将它们加入。

var array = [
    "Make:"+ make,
    "Model:" + model,
    "Date taken: " + dateTime,
    "File name:" + fileName
];
document.getElementById('exifid').innerHTML = array.join('<br/>');

It is much, much better to abstract the data into a readable form using a JavaScript object, like below, if possible. 如果可能的话,使用JavaScript对象将数据抽象为可读形式要好得多。

var variab = {
    "Make": "Audi",
    "Model": "A3",
    "Date Taken": 2006,
    "File Name": "audia3.doc"
}

var string = "";

for (var detail_type in variab){
    var detail_data = variab[detail_type];
    string += detail_type + ": " + detail_data + "<br/>"
}

document.getElementById('exifid').innerHTML = variab;

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

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