字符串转数组 首先想到的是split 方法
let str = '1234567'
console.log(str.split('')) // ["1", "2", "3", "4", "5", "6", "7"]
let str1 = '1,2,3,4,5,6,7'
console.log(str1.split(',')) // ["1", "2", "3", "4", "5", "6", "7"]
后来想到了 Array.from()
用法如下:
let str1 = '123567'
console.log(Array.from(str1)) // ["1", "2", "3", "5", "6", "7"]
但是!!
let str1 = '1,2,3,'
console.log(Array.from(str1)) // ["1", ",", "2", ",", "3", ","]
接下来,谈谈Array.from()
Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。(类数组对象?所谓类数组对象,最基本的要求就是具有length属性的对象。)
let obj = {0:'a',1:'b',length:2}
console.log(Array.from(obj)) // ["a", "b"]
let obj1 = {0:'a',1:'b',length:3} // length属性是可读可写的
console.log(Array.from(obj1)) ["a", "b", undefined]
let obj2 = {0:'a',1:'b',length:1}
console.log(Array.from(obj2)) // ["a"]
let obj = {0:'a',1:'b'}
console.log(Array.from(obj)) //[]
let obj = {
'name': 'tom',
'age': '65',
'sex': '男',
'friends': ['jane','john','Mary'],
length: 4
}
console.log(Array.from(obj)) // [undefined, undefined, undefined, undefined]
let obj = {
0: 'tom',
1: '65',
2: '男',
3: ['jane','john','Mary'],
length: 4
}
console.log(Array.from(obj)) // ["tom", "65", "男", Array(3)]
总结:
1、该类数组对象必须具有length属性,用于指定数组的长度。如果没有length属性,那么转换后的数组是一个空数组。
2、类数组对象的属性名必须为数值型或字符串型的数字