2012-02-09 47 views
2

我有如下多個字符串 -代碼審查 - JavaScript。打破了大串入部分

var str1 = "this is a test that goes on and on"+param1 
var str2 = "this is also a test this is also"+param2+" a test this is also a test this is also a tes" 
var str3 = "this is also a test" 

我指定每個字符串到它自己的變種,以保持代碼的可讀性和防止來自全國各地的字符串尾隨字符串值。此外,作爲我已閱讀,換行JavaScript的漢字不在所有的瀏覽器 - Creating multiline strings in JavaScript

我那麼Concat的琴絃 -

VAR concatStr = STR1 + STR2 + STR3

,並返回字符串拼接值。

這是將大型字符串轉換成其組成部分的可接受的方法。還是可以改進?

回答

6

有沒有必要每一行分配給不同的變量:

var str1 = "this is a test that goes on and on"+param1 + 
    "this is also a test this is also"+param2+ 
    " a test this is also a test this is also a tes" + 
    "this is also a test"; 

就個人而言,我會做到以下幾點:

var string = ['hello ', param1, 
       'some other very long string', 
       'and another.'].join(''); 

對於我來說,它更容易打出來,讀。

1

如果使用很長的字符串,然後按住它的部分在一個數組,然後加入他們的行列:

ARRAY = ['I', 'am', 'joining', 'the', 'array', '!']; 
ARRAY.join(' '); 

和結果:

"I am joining the array !" 

請記住,如果你需要在客戶端JavaScript中執行此操作,那麼您可能會犯錯誤。 :)

+0

+1的「不對勁」的一部分。大塊文本通常不屬於JS程序。 – georg 2012-02-09 11:50:10

0

您可以使用數組。它的連接方法是連接字符串的最快方法。

var myArray = [ 
    "this is a test that goes on and on"+param1, 
    "this is also a test this is also"+param2+" a test this is also a test this is also a tes", 
    "this is also a test" 
]; 

,然後使用:

myArray.join(''); 

讓你完整的字符串。