ArrayLike (AL01)
1: // arguments object (from inside a function)
2: function myFunction() {
3: const args = Array.from(arguments); // Convert arguments to a true array
4: args.forEach(arg => console.log(arg));
5: const mappedArgs = args.map(x => x * 2); // Now .map() and other array function works
6: // ... use any array methods on 'args'
7: }
8:
9: myFunction(1, 2, 3);
In JavaScript, an array-like object is any object that resembles an array but isn't a true Array instance. These objects have the following key characteristics:
1. length Property: They have a length property that specifies the number of elements they contain. This is numerical non-negative integer value.
2. Indexed Elements: Their elements are accessible using numerical indices (0, 1, 2, etc.), similar to how you access elements in true arrays using bracket notation (object[0], object[1], etc.)
3. Lack of Array Methods: Crucially, array-like objects do not have the built-in methods that true arrays possess (e.g., push(), pop(), map(), filter(), forEach()). This is the primary distinction.
Key Differences from True Arrays:
• Methods: Array-like objects don't have the standard array prototype methods. This makes direct manipulation (e.g., using map, filter) impossible without first converting them to true arrays.
• Prototype: Their prototype is not Array.prototype.
• Constructor: Their constructor is not Array.
Converting to a True Array (Most Common):
The Array.from() method is the most straightforward way to convert an array-like object into a true array.
1
2
3
ArrayLike context:
ES6 context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/AL01.htm
|
|