ES6

作者: 命题_1f6e | 来源:发表于2020-07-24 15:05 被阅读0次

Array.from()

Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组
那么什么是类数组对象呢?所谓类数组对象,最基本的要求就是具有length属性的对象。
1、将类数组对象转换为真正数组:

let arrayLike = {
    0: 'tom', 
    1: '65',
    2: '男',
    3: ['jane','john','Mary'],
    'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) // ['tom','65','男',['jane','john','Mary']]
  1. 那么,如果将上面代码中length属性去掉呢?实践证明,答案会是一个长度为0的空数组。
      这里将代码再改一下,就是具有length属性,但是对象的属性名不再是数字类型的,而是其他字
    符串型的,代码如下:
let arrayLike = {
    'name': 'tom', 
    'age': '65',
    'sex': '男',
    'friends': ['jane','john','Mary'],
    length: 4
}
let arr = Array.from(arrayLike)
console.log(arr)  // [ undefined, undefined, undefined, undefined ]

将字符串转换为数组

let  str = 'hello world!';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

相关文章

网友评论

      本文标题:ES6

      本文链接:https://www.haomeiwen.com/subject/rqxhlktx.html