3種轉(zhuǎn)換方法:1、使用split(),可將給定字符串拆分為字符串?dāng)?shù)組,語法“str.split(分隔符,數(shù)組最大長度)”;2、利用擴展運算符“…”,可迭代字符串對象,將其轉(zhuǎn)為字符數(shù)組,語法“[…str]”;3、使用Array.from(),可將字符串轉(zhuǎn)為數(shù)組,語法“Array.from(str)”。
前端(vue)入門到精通課程:進入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點擊使用
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
javascript中將字符串轉(zhuǎn)為數(shù)組的3種方法
-
使用split()
-
利用擴展運算符“…”
-
使用Array.from()
方法1:使用split()方法進行轉(zhuǎn)換
split()方法用于將給定字符串拆分為字符串?dāng)?shù)組;該方法是使用參數(shù)中提供的指定分隔符將其分隔為子字符串,然后一個個傳入數(shù)組中作為元素。
語法:
str.split(separator, limit)
參數(shù):
-
separator:可選。字符串或正則表達式,從該參數(shù)指定的地方分割 string Object。
-
limit:可選。該參數(shù)可指定返回的數(shù)組的最大長度。如果設(shè)置了該參數(shù),返回的子串不會多于這個參數(shù)指定的數(shù)組。如果沒有設(shè)置該參數(shù),整個字符串都會被分割,不考慮它的長度。
示例1:
var str="Welcome to here !"; var n=str.split(""); console.log(n);
示例2:
var str="Welcome to here !"; var n=str.split(" "); console.log(n);
示例3:
var str="Welcome to here !"; var n=str.split("e"); console.log(n);
方法2:利用擴展運算符“...
”
擴展操作符 …
是ES6中引入的,將可迭代對象展開到其單獨的元素中,所謂的可迭代對象就是任何能用for of循環(huán)進行遍歷的對象。
String 也是一個可迭代對象,所以也可以使用擴展運算符 ...
將其轉(zhuǎn)為字符數(shù)組
const title = "china"; const charts = [...title]; console.log(charts); // [ 'c', 'h', 'i', 'n', 'a' ]
進而可以簡單進行字符串截取,如下:
const title = "china"; const short = [...title]; short.length = 2; console.log(short.join("")); // ch
方法3:使用Array.from()方法進行轉(zhuǎn)換
Array.from()方法是javascript中的一個內(nèi)置函數(shù),它從給定的數(shù)組創(chuàng)建一個新的數(shù)組實例。對于字符串,字符串的每個字母表都會轉(zhuǎn)換為新數(shù)組實例的元素;對于整數(shù)值,新數(shù)組實例simple將獲取給定數(shù)組的元素。
語法:
Array.from(str)
示例:
var str="Welcome to here !"; var n=Array.from(str); console.log(n);
【推薦學(xué)習(xí):javascript高級教程】