ES2015数组扩展 - Array.from()

本文介绍了 JavaScript 中 Array.from 方法的基本用法及其应用场景,包括如何将类似数组的对象和可遍历对象转换为真正的数组,并展示了该方法在处理 NodeList 和 arguments 对象方面的实用性。

Array.from方法用于把两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map)。

下面是一个类似数组的对象,Array.from将它转为真正的数组

let arrayLike = {"0":"a","1":"b","2":"c",length:3};

// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a','b','c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a','b','c']

实际应用中,常见的类似数组的对象是DOM操作返回的NodeList集合,以及函数内部的arguments对象,Array.from都可以把它们转为真正的数组。

// NodeList对象
let ps = document.querySelectorAll('p');
Array.from(ps).forEach(function(p){
  console.log(p);
});

// arguments对象
function foo(){
  var args = Array.from(arguments);
  // ...
}

上面的代码中,querySelectorAll方法返回的是一个类似数组的对象,只有讲这个对象转为真正的数组,才能使用forEach方法。

只要是部署了Iterator接口的数据结构,Array.from都能将其转为数组

Array.from('hello');
// ['h','e','l','l','o']

let nameSet = new Set(['a','b']);
Array.from(nameSet) // ['a','b']

上面的代码中,字符串和Set结构都具有Iterator接口,因此可以被Array.from转为真正的数组。

所谓类似数组的对象,本质特征只有一点,即必须有length属性。因此,任何有length属性的对象,都可以通过Array.from方法转为数组

Array.from({length:3});
// [undefined,undefined,undefined]

对于还没有部署该方法的浏览器,可以用Array.prototype.slice方法替代

const toArray = (()=>Array.from ? Array.from : obj=>[].slice.call(obj))();

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,讲处理后的值放入返回的数组

Array.from(arrayLike, x=>x*x);
// 等同于
Array.from(arrayLike).map(x=>x*x);

Array.from([1,2,3], (x)=>x*x)
// [1,4,9]

Array.from()的另一个应用是,将字符串转为数组,然后返回字符串的长度。因为它能够处理各种Unicode字符,可以避免JavaScript将大于\uFFFF的Unicode字符,算作是两个字符的bug

function countSymbols(string){
  return Array.from(string).length;
}
JavaScript: Moving to ES2015 by Ved Antani English | 24 Mar. 2017 | ASIN: B06XWDKLS8 | 1194 Pages | AZW3 | 9.08 MB Explore and master modern JavaScript techniques with ES2015 in order to build large-scale web applications About This Book This course offers an expert's eye on the latest ES6 features and how these advanced tasks fit together in JavaScript as a whole Discover robust JavaScript implementations of classic and advanced design patterns Learn about modern web architectures and build real-world apps on top of them Who This Book Is For This course is for experienced developers familiar with other object-oriented languages who wants to learn new capabilities of ES-2015 to improve their web development skills and build professional-quality web applications. This also goes for those who want to explore some modern JavaScript features, techniques, and architectures in order to develop cutting-edge web applications. What You Will Learn Get a run through of the basic language constructs, Functions, and Closures of JavaScript Code using the powerful object-oriented feature in JavaScript Master DOM manipulation, cross-browser strategies, and ES6 Harness the power of patterns for tasks ranging from application building to code testing Identify the best use cases for microservices Gain expertise in responsive and dynamic website design Enable real-time communications between client-client and client-server/server-client Write complete applications using functional reactive programming In Detail JavaScript is a high-level, dynamic, untyped, lightweight, and interpreted programming language. Mastering modern JavaScript techniques and the toolchain are essential to develop web-scale applications. This Learning Path will upgrade your skills to ES2015, and you will get to introduce yourself to popular frameworks like React and Angular 2. In the first module, you will get familiar with the language constructs and how to make code easy to organize. You will gain a concrete understanding of variable scoping, loops, and best practices on using types and data structures, as well as the coding style and recommended code organization patterns in JavaScript. By the end of the module, you will understand how reactive JavaScript is going to be the new paradigm. Over the course of the next module, you will explore how design patterns can help you improve and organize your JavaScript code. You'll get to grips with creational, structural, and behavioral patterns and get a deeper look at patterns used in functional programming, as well as model view patterns and patterns to build web applications. By the end of the module, you'll be saved of a lot of trial and error and developmental headaches, and you will be on the road to becoming a JavaScript expert. In the last leg of this course, you will shift your focus to network programming concepts as you build a real-time web application with websockets. Along the way, you'll explore how the power of JavaScript can be increased multi-fold with high performance techniques. By the end of this module, you'll be a skilled JavaScript developer with a solid knowledge of the latest JavaScript techniques, tools, and architecture to build modern web apps. This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products: Mastering JavaScript by Ved Antani Mastering JavaScript Design Patterns, Second Edition by Simon Timms Modern JavaScript Applications by Narayan Prusty Style and approach This course is a comprehensive guide with a clear focus on practical use cases and patterns. Each chapter consists of best practices, useful advice, and a bunch of easy-to-follow examples that will build up your skills as you advance.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值