天天看点

字符串转数组还用split?(es6:Array.from())

js中字符串转换成数组的最新方法

在读了es6的新语法之后,一搜这个问题,发现多数人竟然还在用,拼接来完成,那么最新的办法是什么呢?

Array.from()

//字符串转换成数组
let str = 'qqwweertyuiop'
console.log(Array.from(str))
//["q","q","w","w","e","e","r","t","y","u","i","o","p"]
           

是不是太简单了!!!

当然还有其他的用法

//将类数组对象或可迭代对象转化为数组
// 参数为数组,返回与原数组一样的数组
console.log(Array.from([1, 2])); // [1, 2]
 
// 参数含空位
console.log(Array.from([1, , 3])); // [1, undefined, 3]
           
//map 函数 用于对每个元素进行处理,放入数组的是处理后的元素。
console.log(Array.from([1, 2, 3], (n) => n * 2)); // [2, 4, 6]
           
//用于指定 map 函数执行时的 this 对象。

let map = {
    do: function(n) {
        return n * 2;
    }
}
let arrayLike = [1, 2, 3];
console.log(Array.from(arrayLike, function (n){
    return this.do(n);
}, map)); // [2, 4, 6]
           
//类数组对象
//一个类数组对象必须含有 length 属性,且元素属性名必须是数值或者可转换为数值的字符。
let arr = Array.from({
  0: '1',
  1: '2',
  2: 3,
  length: 3
});
console.log(); // ['1', '2', 3]
 
// 没有 length 属性,则返回空数组
let array = Array.from({
  0: '1',
  1: '2',
  2: 3,
});
console.log(array); // []
 
// 元素属性名不为数值且无法转换为数值,返回长度为 length 元素值为 undefined 的数组  
let array1 = Array.from({
  a: 1,
  b: 2,
  length: 2
});
console.log(array1); // [undefined, undefined]