与字符串

时间:2017-10-03 16:59:25

标签: javascript variables concatenation

我刚刚开始我的学习过程,现在被困在这个字符串上。我搜索了MDN,Google和Bing,但没有找到任何帮助。

我的代码说明告诉我分配一个变量,我做了。然后它要我在console.log中测试。我已经这样做了,当我处理空格和标点符号时,它会给我一个错误,说它需要一个标识符,而不是看到' +'。

如果我拿出标点符号,我没有错误,但没有标点符号。如果我拿出额外的空格以及标点符号,我会得到一个奇怪的连续句子,但没有错误。我在Udacity中解决了这个问题,这是第2课的测验。

我的代码是:

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1. +  " James and Julia are so " +  adjective2. +  " I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib); 

2 个答案:

答案 0 :(得分:2)

您还需要将点添加为字符串。

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1 + "."
        + " James and Julia are so " +  adjective2 + "."
        + " I cannot wait to work through the rest of this " +  adjective3 +  " content!";
    
console.log(madLib);

.在Javascript中具有特殊含义。它作为对象属性的访问器。

Math.floor(1.5); // return the integer value of the given number

在此处详细了解property accessor

答案 1 :(得分:0)

添加。 (点)在字符串的双引号部分内,而不是在变量旁边。

它是字符串的一部分,而不是内存中的变量。而那之后你就没有任何功能。

以下代码段正常运行。



var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1 +  ". James and Julia are so " +  adjective2 +  ". I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib); 




使用dot调用函数的示例。在这种情况下不需要它,因为它已经是一个字符串。



var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1.toString() +  ". James and Julia are so " +  adjective2.toString() +  ". I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib);