美文网首页
9.`Array.from()` 和 `Array.of()`

9.`Array.from()` 和 `Array.of()`

作者: dptms | 来源:发表于2017-10-27 14:14 被阅读19次

Array.from()Array.of()

这两个函数的操作对于我们一些常见的操作和流程判断是非常方便有用的。他们并不是原型上的方法

Array.from()用于把类数组对象,或一个可遍历对象转换为一个真正的数组

类数组对象就是拥有 length 属性的对象
可遍历对象就是部署了可遍历接口 iterable 的对象

// 拥有 `length` 属性的nodelist对象
const todos = document.querySelectorAll('li');
const todosArr = Array.from(todos); // 将类数组对象转换为真是数组
const names = todosArr.map(todo=>todo.textContent);
console.log(name);

// 以上可以简写为,转换为数组后相当于调用了 `map` 方法
const name = Array.from(todos, todo => todo.textContent);

// 拥有 `length` 属性的arguments对象
function sum() {
    return Array.from(arguments).reduce((prev, curr) => prev + curr, 0);
}

// 字符串
const str = 'laravel';
console.log(Array.from(str));

Array.of()返回有参数组成的数组

new Array(3) 是创建一个长度为3的数组,而不是元素为3的数组
Array.of() 返回结果一致性,Array.of(3) 创建的就是一个元素为3的数组

相关文章

  • 9.`Array.from()` 和 `Array.of()`

    Array.from() 和 Array.of() 这两个函数的操作对于我们一些常见的操作和流程判断是非常方便有用...

  • Array.of() 和 Array.from()

    let a = Array.from(3) console.log(a) //length 为3的数组 a[0] ...

  • es6数组拓展

    Array.of方法 es6之前数组有个怪异的行为: array.of可以解决这个问题: Array.from 定...

  • es6-数组扩展

    数组新增特性 Array.from Array.of copyWithin find\findIndex fill...

  • Array方法总结

    Array.length Array.from() : Array.isArray() Array.of() co...

  • ES6学习——数组的扩展

    总结 1. Array.from() : 将类数组对象和可遍历对象转化为真正的数组 2. Array.of() :...

  • 数组扩展

    1,扩展运算符2,Array.from()3,Array.of()4,数组实例的 copyWithin()5,数组...

  • ES6之数组的扩展

    Array.of( ) 将一组数值转换为数组,用来弥补Array()的不足。 Array.from( ) 将伪数组...

  • 数组

    新方法:Array.of() 将参数中所有值作为元素形成数组。 Array.from()[https://www...

  • ES6 扩展字符串数组对象常用方法整理

    数组扩展 Array.from() 将类数组对象和可遍历对象转换成数组 Array.of() 将一组值转换为数组 ...

网友评论

      本文标题:9.`Array.from()` 和 `Array.of()`

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