2011-03-08 26 views
0

我在JavaScript中使用split(' ')方法來散佈空白字。 例如:如何將Char轉換爲JavaScript中的字符串?

我有文字,如:

var str ="Hello this is testing" 

我打電話

str.split(' ') 

後,現在我會得到你好,這是tesing作爲輸出,當我做這個

str[2] 

我得到「l」,但我想得到「測試」字(按照數組索引)。如何STR轉換爲數組,所以如果我把

str[2] //It should be testing. 
+0

aravinth海峽[2]應該是單詞「是」由你希望現在達到 –

回答

6
var a = str.split(" "); // split() returns an array, it does not modify str 
a[2]; // returns "is"; 
a[3]; // returns "testing"; 
+0

感謝我得到了什麼:) –

2

字符串是不可變的,split[docs]回報的數組。您必須將返回值分配給一個變量。例如:

> var str ="Hello this is testing"; 
    undefined 
> str = str.split(' '); 
    ["Hello", "this", "is", "testing"] 
> str[3] 
    "testing" 
+1

感謝你的回覆! –

7

當你做分割它實際上返回一個值。

var foo = str.split(' '); 
foo[2] == 'is' // true 
foo[3] == 'testing' // true 
str[2] == 'l' // because this is the old str which never got changed. 
+2

除了'foo [2]'實際上等於「是」。 – gilly3

+0

'str [2]'實際上等於'l' – jondavidjohn

+0

Woops你是對的。我正在複製作者的建議:P –

2

寫入str.split(" ")不修改str
相反,它返回一個包含單詞的新數組。

你可以寫

var words = str.split(" "); 
var aWord = words[1]; 
+0

謝謝我現在:) –

3

.split()正在恢復你的陣列,它不改變現有的變量

例子的價值...

var str = "Hello this is testing"; 

var str_array = str.split(' '); 

document.write(str_array[3]); //will give you your expected result. 
+0

現在感謝我得到:) –

2

我做了這個網站並報告以下內容:

function getStrs() 
{ 
    var str = "Hello this is testing"; 
    var array = str.split(' '); 
    for(var i=0; i < 4; i ++) 
     alert(array[i]); 
} 

據報道喂...這...是... ...測試

+0

感謝您的回覆! –