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) ".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
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: 'a', 1: 'b', 2: 'c', }; 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>
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);
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 = { '1': 5, '2': 8, '3': 4, '4': 6 }; //内置对象Object.keys:获取键 var arr = Object.keys(obj) console.log(arr); //内置对象Object.values获取值 var arr2 = Object.values(obj) console.log(arr2);
## The third method: Array.from( )
let obj = { '0': 5, '1': 8, '2': 4, '3': 6, 'length':4 }; let arr = Array.from(obj) console.log(arr);
Array.from() converts the object into an array and must meet 2 conditions
When length is not written:1: The key must be a numerical value
2: A key-value pair that must have length
##Expand knowledge: the difference between for of, for in and forEach let arr = ['周一', '周二', '周三', '周四','周五','周六','周日']
// 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:
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 return
3.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
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:
(1) The parameter is the traversed array content ( Required)
(2) The parameter is the corresponding array index (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!

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

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

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

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

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

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'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

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


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

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
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
