天天看點

字元串轉換成字元數組的一些方法1. split()2. 擴充運算符3. 字元串的解構指派4. Array.from

内容基本源自某公衆号,在其基礎上進行了部分補充

字元串轉為字元數組的一些方法

  • 1. split()
  • 2. 擴充運算符
  • 3. 字元串的解構指派
  • 4. Array.from

1. split()

split()

用于把一個字元串分割成字元數組,有兩個參數

separator

howmany

  • separator

    必需,字元串 / 正規表達式,⚠️傳回的字元串數組中并不包含

    separator

    本身
  • howmany

    可選,用于指定傳回數組的最大長度,若未設定

    howmany

    ,整個字元串都會被分割
const str1 = "How are you?"; 

// 空字元串分割
console.log(str1.split("")); // (12) ["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", "?"]

// 空格分割
console.log(str1.split(" ")); // (3) ["How", "are", "you?"]

// 空字元串分割,傳回的數組最大長度為3
console.log(str1.split("",3)); // (3) ["H", "o", "w"]

const str2 = "|a|b|c|";

console.log(str2.split("|"));   // ["", "a", "b", "c", ""]
// 首|實際上分割的是空字元和字元a,尾|實際上分割的是字元c和空字元
           

由上面例子,可知:使用空字元串("")做為

split()

separator

,字元串中的每個字元之間都會被分割,可以将字元串轉換為字元數組。

const text = "hello";
console.log(text.split(""));	// (5) ["h", "e", "l", "l", "o"]
           

⚠️:但是

split()

無法正常處理,采用兩個代碼單元的字元,比如表情字元

const text = "hello😎";
console.log(text.split(""));	// (7) ["h", "e", "l", "l", "o", "\ud83d", "\ude0e"]
           

2. 擴充運算符

(ES6新特性)

擴充運算符

(...)

将一個數組轉為用逗号分隔的參數序列

const arr = [1,2,3];
console.log(...arr);	// 1 2 3
           

實際上我們可以利用擴充運算符幹很多事情,這裡就隻介紹展開運算符 ( …) 可以用于展開字元串

const text = "hello";
console.log(...text);	// h e l l o
console.log([text]);	// ["hello"]
console.log([...text]); // (5) ["h", "e", "l", "l", "o"]
           

擴充運算符可以正确處理采用兩個代碼單元的字元:

const text = "hello😎";
console.log([...text]);		// (6) ["h", "e", "l", "l", "o", "😎"]
           

3. 字元串的解構指派

ES6 允許按照一定模式,從數組和對象中提取值,對變量進行指派,這被稱為解構

數組、對象、數值、布爾值都可以進行解構指派,字元串也可以進行解構指派,是因為此時字元串被轉換成了一個類似數組的對象

const [a, b, c, d, e] = "hello";
console.log([a, b, c, d, e]);	// (5) ["h", "e", "l", "l", "o"]

const [a, b, c, d, e, f] = "hello😎";
console.log([a, b, c, d, e, f]);	// (6) ["h", "e", "l", "l", "o", "😎"]

// 結合擴充運算符使用
const text = "hello😎";
const [...chars] = text;
console.log(chars);		// (6) ["h", "e", "l", "l", "o", "😎"]
           

4. Array.from

(ES6新特性)

Array.from

方法用于将兩類對象轉為真正的數組:類似數組的對象(array-like object)和可周遊(iterable)的對象(包括 ES6 新增的資料結構 Set 和 Map)

// 類數組對象
const arrayLike = {
	'0': 'a',
	'1': 'b',
	'2': 'c',
	length: 3
}
console.log(Array.from(arrayLike));		// (3) ["a", "b", "c"]

// 字元串
const text = "hello😎";
console.log(Array.from(text));		// (6) ["h", "e", "l", "l", "o", "😎"]
           

⚠️:

  • 擴充運算符背後調用的是

    周遊器接口

    (

    Symbol.iterator

    ),如果一個對象沒有部署這個接口,就無法轉換。
  • 但是

    Array.from()

    方法還支援類數組對象,所謂類數組對象就是必須有

    length

    屬性。
  • 是以所有有

    length

    屬性的對象都可以通過

    Array.from()

    方法轉為數組,但此時擴充運算符就無法轉換

繼續閱讀