search
HomeWeb Front-endFront-end Q&AWhat is a pseudo array in javascript

What is a pseudo array in javascript

Oct 19, 2021 pm 04:47 PM
javascript

In JavaScript, a pseudo-array, also known as an array-like object, is an array-like object that stores data according to an index and has a length attribute; because it is an object, the pseudo-array does not have the push of an array. (), forEach() and other methods.

What is a pseudo array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Definition and characteristics of pseudo array

Pseudo array (ArrayLike), also known as array-like. Is an array-like object that stores data according to index and has a length property. But it has the following characteristics.

  • Storing data by index

    0: xxx, 1: xxx, 2: xxx...

  • Has the length attribute

    But the length attribute is not dynamic and will not change as the members change

  • Methods such as push() and forEach() without arrays

    arrayLike.__proto__ === Object.prototype;   //true 
    arrayLike instanceof Object; //true 
    arrayLike instanceof Array; //false

Common typical pseudo-arrays, including the set of DOM elements obtained through $() in jQuery, functions The arguments object, and the String object.

Example:

    var arrLike = {
        0: 'a',
        1: 'b',
        2: 'c',
        length: 3,
    }
    arrLike[1]; //'a'
    arrLike.length; //3
    arrLike.push('d'); //Uncaught TypeError: arrLike.push is not a function

How to convert a pseudo array into a real array

    var arrLike = {
        0: 'a',
        1: 'b',
        2: 'c',
        length: 3,
    };

1. Traverse and add an empty array

    var arr = [];
    for(var i = 0; i < arrLike.length; i++){
        arr.push(arrLike[i]);
    }

Relatively simple and easy to understand, but the steps are a bit cumbersome.

2. Use slice() method of array [Recommended]

    ;[].slice.call(arrLike);

or

    Array.prototype.slice.apply(arrLike);

Use slice() to return a new array, use call() or apply() points its scope to a pseudo array.

Note that no additional attributes other than the index value will be retained in the returned array.

For example, the context attribute in the DOM pseudo array obtained by $() in jQuery will not be retained after being converted by this method.

Simulate the internal implementation of slice()

    Array.prtotype.slice = function(start, end){
        var result = new Array();
        var start = start | 0;
        var end = end | this.length;
        for(var i = start; i < end; i++){
            result.push(this[i]);
        }
        return result;
    }

3. Modify the prototype pointer

    arrLike.__proto__ = Array.prototype;

In this way, arrLike inherits the method in Array.prototype , you can use push(), unshift() and other methods, and the length value will also change dynamically.

In addition, this method of directly modifying the prototype chain will also retain all attributes in the pseudo array, including attributes that are not index values.

4. The Array.from() method in ES2015

The Array.from() method creates a new array instance from an array-like or iterable object. .

    var arr = Array.from(arrLike);

The result obtained is similar to the second method, only the attributes within the index value are retained.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What is a pseudo array in javascript. 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
Mastering CSS Selectors: Class vs. ID for Efficient StylingMastering CSS Selectors: Class vs. ID for Efficient StylingMay 16, 2025 am 12:19 AM

The use of class selectors and ID selectors depends on the specific use case: 1) Class selectors are suitable for multi-element, reusable styles, and 2) ID selectors are suitable for unique elements and specific styles. Class selectors are more flexible, ID selectors are faster to process but may affect code maintenance.

HTML5 Specification: Exploring the Key Goals and MotivationsHTML5 Specification: Exploring the Key Goals and MotivationsMay 16, 2025 am 12:19 AM

ThekeygoalsandmotivationsbehindHTML5weretoenhancesemanticstructure,improvemultimediasupport,andensurebetterperformanceandcompatibilityacrossdevices,drivenbytheneedtoaddressHTML4'slimitationsandmeetmodernwebdemands.1)HTML5aimedtoimprovesemanticstructu

CSS IDs and Classes : a simple guideCSS IDs and Classes : a simple guideMay 16, 2025 am 12:18 AM

IDsareuniqueandusedforsingleelements,whileclassesarereusableformultipleelements.1)UseIDsforuniqueelementslikeaspecificheader.2)Useclassesforconsistentstylingacrossmultipleelementslikebuttons.3)BecautiouswithspecificityasIDsoverrideclasses.4)Useclasse

HTML5 Goals: Understanding the Key Objectives of the SpecificationHTML5 Goals: Understanding the Key Objectives of the SpecificationMay 16, 2025 am 12:16 AM

HTML5aimstoenhancewebaccessibility,interactivity,andefficiency.1)Itsupportsmultimediawithoutplugins,simplifyinguserexperience.2)Semanticmarkupimprovesstructureandaccessibility.3)Enhancedformhandlingincreasesusability.4)Thecanvaselementenablesdynamicg

Is it difficult to use HTML5 to achieve its goals?Is it difficult to use HTML5 to achieve its goals?May 16, 2025 am 12:06 AM

HTML5isnotparticularlydifficulttousebutrequiresunderstandingitsfeatures.1)Semanticelementslike,,,andimprovestructure,readability,SEO,andaccessibility.2)Multimediasupportviaandelementsenhancesuserexperiencewithoutplugins.3)Theelementenablesdynamic2Dgr

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

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 Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool