📜 ⬆️ ⬇️

Array-Like Objects

What is it?
Few know that JavaScript has an entity like Array-Like Objects.

That is, everyone knows that there are such things as document.images, document.getElementsByTageName, arguments in the context of a function call, and so on.

But not everyone knows how this entity can be used, for example - one can bring such entities to full-fledged arrays (through copying), with all the ensuing possibilities.
')
Usually Array-Like Object distinguishes "Object" as a constructor, and length - which is inherited by the prototype (it is not clear where it is from - for me it remains a mystery) :)

To specifics :
 // Copy function with conversion
 var cloneAsArray = function (arrayLikeObject) {
     var isArrayLikeObject = (
         typeof arrayLikeObject === 'object' &&
         typeof arrayLikeObject.length === 'number'
     );
    
     if (isArrayLikeObject) {
         return Array.prototype.slice.call (arrayLikeObject)
     }
 };

 // usage example
 var testFuction = function () {
     // It is necessary to get into the internal function all the arguments passed except the first array
     var _args = cloneAsArray (arguments) .slice (1);
    
     return _args;
 }

 console.log (testFuction (7,1,2,3,4)) 

Minuses:
Yes, this is a copy of the object that affects the use of memory, of course.

Pros:
You can avoid large loops in this way if you need some kind of transformation over an Array-Like Object.
Type saving on CPU

Summary:
Apply thoughtfully :)

Source: https://habr.com/ru/post/44601/


All Articles