js字符串转数组
字符串转数组 ⾸先想到的是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、类数组对象的属性名必须为数值型或字符串型的数字
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论