天天看点

字符串转换成字符数组的一些方法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()

    方法转为数组,但此时扩展运算符就无法转换

继续阅读