[英]How to convert Char into Strings in JavaScript?
我在JavaScript中使用split(' ')
方法將單詞泛濫為空格。 例如:
我有這樣的文字:
var str ="Hello this is testing"
我打電話之后
str.split(' ')
現在,我將得到Hello,它正在作為輸出,當我這樣做時
str[2]
我得到“ l”,但我想得到“ 測試 ”字(按數組索引)。 如何將str轉換為數組,以便如果我把
str[2] //It should be testing.
拆分后,它實際上會返回一個值。
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.
var a = str.split(" "); // split() returns an array, it does not modify str
a[2]; // returns "is";
a[3]; // returns "testing";
.split()
返回您的數組,它不會更改現有變量的值
例...
var str = "Hello this is testing";
var str_array = str.split(' ');
document.write(str_array[3]); //will give you your expected result.
字符串不可變, split
[docs] 返回一個數組。 您必須將返回值分配給變量。 例如:
> var str ="Hello this is testing";
undefined
> str = str.split(' ');
["Hello", "this", "is", "testing"]
> str[3]
"testing"
編寫str.split(" ")
不會修改str
。
而是返回一個包含單詞的新數組。
你可以寫
var words = str.split(" ");
var aWord = words[1];
我做了這個html頁面,它報告了以下內容:
function getStrs()
{
var str = "Hello this is testing";
var array = str.split(' ');
for(var i=0; i < 4; i ++)
alert(array[i]);
}
報告了您好...這是...測試中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.