我在Javascript中打印一些连接字符串时遇到问题

时间:2016-07-25 00:39:25

标签: javascript string-concatenation

var quotePt1 = "Excellence is an art won by training and    
                habituation.";
var quotePt2 = "We do not act rightly because we have virtue or     
                excellence,";
var quotePt3 = "but we rather have those because we have acted 
                rightly.";
var quotePt4 = "We are what we repeatedly do.";
var quotePt5 = "Excellence, then, is not an act but a habit.";
var qouteFull = quotePt1.concat(quotePt2+quotePt3+quotePt4+quotePt5); 

我试图将完整的引用名称指定为" quoteFull'然后打印整个报价

3 个答案:

答案 0 :(得分:0)

我不确定您是否知道所有拼写错误。

暂且不说,为什么不使用+连接它们,而不是使用concat()



var quotePt1 = "Excellence is an art won by training and habituation. ";

var quotePt2 = "We do not act rightly because we have virtue or excellence, ";

var quotePt3 = "but we rather have those because we have acted rightly. ";

var quotePt4 = "We are what we repeatedly do. ";

var quotePt5 = "Excellence, then, is not an act but a habit.";

var qouteFull = quotePt1 + quotePt2 + quotePt3 + quotePt4 + quotePt5;

console.log(qouteFull);




答案 1 :(得分:0)

正如其他受访者回答的那样,要在JavaScript中连接字符串,请使用 +

但是,使用递增整数命名的变量对我来说就像一个数组,它可以这样编码:

var quotePts = ["Excellence is an art won by training and habituation.",
    "We do not act rightly because we have virtue or excellence,",
    "but we rather have those because we have acted rightly.",
    "We are what we repeatedly do.",
    "Excellence, then, is not an act but a habit."];
var quoteFull = quotePts.join("\n",quotePts);
console.log(quoteFull);

为了完整性,如果你想使用多行字符串,你可以在每一行的末尾使用反斜杠,如下所示:

var quoteFull = "Excellence is an art won by training and habituation. \n\
We do not act rightly because we have virtue or excellence, \n\
but we rather have those because we have acted rightly. \n\
We are what we repeatedly do. \n\
Excellence, then, is not an act but a habit.";
console.log(quoteFull);

信用:https://davidwalsh.name/multiline-javascript-strings

答案 2 :(得分:0)

var quotePt1 = "Excellence is an art won by training and habituation.";
var quotePt2 = " We do not act rightly because we have virtue or     
                 excellence,";
var quotePt3 = " but we rather have those because we have acted  
                 rightly.";
var quotePt4 = " We are what we repeatedly do.";
var quotePt5 = " Excellence, then, is not an act but a habit.";
var quoteFull = quotePt1 + quotePt2 + quotePt3 + quotePt4 + quotePt5;

的console.log(quoteFull);

这是正确的答案。仅供参考。我只需要纠正我的拼写,并在第一次引用后在行之间添加一个空格。我正在通过BLOC软件开发人员课程,我认为该课程对语法非常具体。呼!