[解构赋值-04]字符串的结构赋值
2018-12-24 本文已影响1人
飞蝗tengda
const str = 'I am the bone of my sword'; // 我是剑骨头
我们可以用数组的解构赋值来对字符串进行结构赋值。
所以变量的取值需要位置决定
//这样我们就得到
//a = "I"
//b = " "
//c = a
const [ a, b ,c] = str;
同样,我们可以用到扩展运算符
//扩展运算符会把剩余的字符组成为一个数组赋值给oth
//["m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
const [ a, b ,c, ...oth ] = str;
运用
- 分解字符串
这三种方式得到的结果一样
const [ ...spStr1 ] = str;
const spStr2 = str.split('');
//扩展运算符合并数组的方式再赋值给变量spStr3
const spStr3 = [ ...str ];
- 提取字符串的属性和方法
//取字符串的length属性和split方法
const { length, split } = str;
const { length, split } = str;