search
HomeWeb Front-endFront-end Q&AHow to convert array-like object to array in es6

Conversion method: 1. Use the "for in" statement to convert the array-like object into an array, the syntax is "for(var i in obj){console.log(arr.push(obj[i])); }"; 2. Use the built-in object keys and values, the syntax "Object.keys(obj)" and "Object.values(obj)"; 3. Use the from() function of the Array object, the syntax "Array.from(obj) ".

How to convert array-like object to array in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

#What is an array class?

There are some objects in JavaScript that look like but are not arrays, called array-like objects.

#What is an array-like object?

only contains integers starting from 0 and naturally increasing integers as keys, and also defines length objects used to represent the number of elements. is usually considered to be a -like array object.

  • has a numeric index subscript pointing to the object element, and the length attribute tells us the number of elements in the object;

  • does not have For example, array objects such as push, forEach and indexOf have methods;

Convert class array to array

First method: Use for in to convert an array-like object into an array

<script type="text/javascript">
		var obj = {
			0: &#39;a&#39;,
			1: &#39;b&#39;,
			2: &#39;c&#39;,
		};
		console.log(obj[0]);
		console.log(typeof obj);
		var arr = [];
		for(var i in obj){
			console.log(arr.push(obj[i]));
		}
		console.log(arr);
		//把类数组对象放在一个名为arr的新数组里使得obj变成了数组

		console.log(arr instanceof Array);//判断arr是否为数组

	</script>

How to convert array-like object to array in es6

If you want to get the entire object:

let arr1 = []
		for (let i in obj) {
			let newobj = {}
			newobj[i] = obj[i]
			arr1.push(newobj);
		}
		console.log(arr1);

How to convert array-like object to array in es6

The second method: built-in object keys and values

Built-in object Object.keys: Get the key

Built-in object Object.values ​​gets the value

let obj = {
			&#39;1&#39;: 5,
			&#39;2&#39;: 8,
			&#39;3&#39;: 4,
			&#39;4&#39;: 6
		};
		//内置对象Object.keys:获取键
		var arr = Object.keys(obj)
		console.log(arr);
		//内置对象Object.values获取值
		var arr2 = Object.values(obj)
		console.log(arr2);

How to convert array-like object to array in es6

## The third method: Array.from( )

let obj = {
		&#39;0&#39;: 5,
		&#39;1&#39;: 8,
		&#39;2&#39;: 4,
		&#39;3&#39;: 6,
		&#39;length&#39;:4
	};
	    let arr = Array.from(obj)
		console.log(arr);

Array.from() converts the object into an array and must meet 2 conditions

1: The key must be a numerical value

2: A key-value pair that must have length

When length is not written:

When adding length key-value pairs:

How to convert array-like object to array in es6

##Expand knowledge: the difference between for of, for in and forEach

let arr = [&#39;周一&#39;, &#39;周二&#39;, &#39;周三&#39;, &#39;周四&#39;,&#39;周五&#39;,&#39;周六&#39;,&#39;周日&#39;]
		// for of
		for (let item of arr) {
			console.log(item);
		}
        // for in
		for (let i in arr) {
			console.log(i);
		}
        // forEach
        arr.forEach(item => {
			console.log(item);
		})
The effect is as shown in the figure:


How to convert array-like object to array in es6

for of item represents the array A certain item

i in for in represents the index, which is generally used to traverse the object

The forEach method is used to call each element of the array , and pass the element to the callback function.

for of

1. You can avoid all the traps in

for-in

loops2. You can Using
break, continue and return3.for-of
loops supports more than just array traversal. It is also applicable to many array-like objects4. It also supports string
traversal5.for-of is not suitable for processing original native objects

for in

Note: the for..in loop will traverse the methods and properties in the prototype of a certain type, so this may cause problems in the code Unexpected error

for Each

##1,

foreach

method cannot use return, break, continue statements to jump out Loop 2. The function callback in the forEach method has three parameters:

How to convert array-like object to array in es6 (1) The parameter is the traversed array content ( Required) (2) The parameter is the corresponding array index (optional)

(3) The parameter is the array itself (optional)


3. Execute the provided element once for each element of the array function. Return undefined

[Recommended learning: javascript video tutorial]

The above is the detailed content of How to convert array-like object to array in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment