javascript from() 方法将一个类数组对象转换成真实的数组
<strong>Array.from()</strong>
方法可以将一个类数组对象或可迭代对象转换成真实的数组。
from语法
<code class="language-javascript">Array.from(arrayLike[, mapFn[, thisArg]]) </code>
from参数
参数 | 说明 |
arrayLike | 想要转换成真实数组的类数组对象或可迭代对象。 |
mapFn | 可选参数,如果指定了该参数,则最后生成的数组会经过该函数的加工处理后再返回。 |
thisArg | 可选参数,执行 mapFn 函数时 this 的值。 |
你可以使用 Array.from()
将下面的两种对象转换成数组:
- 类数组对象(拥有一个
length
属性和若干索引属性的任意对象) - 可迭代对象(你可以从它身上迭代出若干个元素的对象,比如有
Map
和Set
等)
Array.from()
方法有一个可选参数 mapFn
,让你可以在最后生成的数组上再执行一次 map
方法后再返回。也就是说 Array.from(obj, mapFn, thisArg)
就相当于 Array.from(obj).map(mapFn, thisArg),
除非创建的不是可用的中间数组。 这对一些数组的子类,
如 typed arrays 来说很重要, 因为中间数组的值在调用 map() 时需要是适当的类型。
from()
的 length
属性为 1 。
from
实例:
<code class="language-javascript">// 将类数组对象(arguments)转换成数组 (function () { var args = Array.from(arguments); return args; })(1, 2, 3); // [1, 2, 3] // 将可迭代对象(Set 对象)转换成数组 Array.from(Set(["foo", window])); // ["foo", window] // Map 对象也可以 var m = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(m); // [[1, 2], [2, 4], [4, 8]] // 字符串对象既是类数组又是可迭代对象 Array.from("foo"); // ["f", "o", "o"] // 使用 map 函数转换数组元素 Array.from([1, 2, 3], x => x + x); // [2, 4, 6] // 生成一个数字序列 Array.from({length:5}, (v, k) => k); // [0, 1, 2, 3, 4]</code>
from兼容性解决方法
ECMA-262 第六版标准添加了 Array.from
。有些实现中可能尚未包括。你可以通过在脚本前添加如下内容作为替代方法,以使用未原生支持的 Array.from
方法。该算法按照 ECMA-262 第六版中的规范实现,并假定Object
和 TypeError
有其本身的值, callback.call
对应 Function.prototype.call
。此外,鉴于无法使用 Polyfill 实现真正的的迭代器,该实现不支持规范中定义的泛型可迭代元素。
<code class="language-javascript">// Production steps of ECMA-262, Edition 6, 22.1.2.1 // Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from if (!Array.from) { Array.from = (function () { var toStr = Object.prototype.toString; var isCallable = function (fn) { return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; }; var toInteger = function (value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var maxSafeInteger = Math.pow(2, 53) - 1; var toLength = function (value) { var len = toInteger(value); return Math.min(Math.max(len, 0), maxSafeInteger); }; // The length property of the from method is 1. return function from(arrayLike/*, mapFn, thisArg */) { // 1. Let C be the this value. var C = this; // 2. Let items be ToObject(arrayLike). var items = Object(arrayLike); // 3. ReturnIfAbrupt(items). if (arrayLike == null) { throw new TypeError("Array.from requires an array-like object - not null or undefined"); } // 4. If mapfn is undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); // 16. Let k be 0. var k = 0; // 17. Repeat, while k </code>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

In this article, we will show you how to convert OpenDocumentTextDocument (ODT) files to Microsoft Word (Docx, DOC, etc.). Format. How to Convert ODT to Word in Windows 11/10 Here is how you can convert ODT documents to DOC or DOCX format on Windows PC: Convert ODT to Word using WordPad or Word The first method we are going to show you Is to use WordPad or MicrosoftWord to convert ODT to Word. Here are the steps to achieve this: First, open the WordPad app using the Start menu. Now, go to

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

AI files refer to vector graphics files created by Adobe Illustrator (AI for short) software, while CDR files refer to vector graphics files created by CorelDRAW software. Since these two softwares are developed by different manufacturers, their file formats are different and cannot be directly converted to each other. However, we can convert AI files to CDR files through some methods. A commonly used conversion method will be introduced below. Step 1: Export AI files to EPS format AdobeIllust

Converting a virtual machine (VM) to a physical machine is the process of migrating a virtual instance and associated application software to a physical hardware platform. This conversion helps optimize operating system performance and hardware resource utilization. This article aims to provide an in-depth look at how to make this conversion. How to implement migration from virtual machine to physical machine? Typically, the conversion process between a virtual machine and a physical machine is performed outside the virtual machine by third-party software. This process consists of multiple stages involving the configuration of virtual machines and the transfer of resources. Prepare the physical machine: The first step is to ensure that the physical machine meets the hardware requirements for Windows. We need to back up the data on a physical machine as the conversion process will overwrite the existing data. *Username and password for an administrator account with administrator rights to create system images. will be virtual

Golang time conversion: How to convert timestamp to string In Golang, time operation is one of the very common operations. Sometimes we need to convert the timestamp into a string for easy display or storage. This article will introduce how to use Golang to convert timestamps to strings and provide specific code examples. 1. Conversion of timestamps and strings In Golang, timestamps are usually expressed in the form of integer numbers, which represent the number of seconds from January 1, 1970 to the current time. The string is

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]
