Array-like object
In JavaScript, array-like objects are a common structure that resemble arrays but are not true arrays. These objects typically have numeric indices and a length
property but lack native array methods. Understanding the characteristics and conversion methods of array-like objects allows for more flexible data handling.
What is an Array-like Object?
An array-like object (Array-like Object) is an object with the following features:
- Has numeric indices starting from
0
; - Has a
length
property; - Does not inherit from
Array.prototype
, so it cannot directly call array methods (e.g.,push
,pop
, etc.).
Typical array-like objects include:
- The
arguments
object in functions; NodeList
returned by DOM operations (e.g., the result ofdocument.querySelectorAll
);- Strings (each character can be accessed via an index).
// Example: arguments object
function showArgs() {
console.log(arguments); // Array-like object
console.log(arguments.length); // 3
console.log(arguments[0]); // 'a'
}
showArgs('a', 'b', 'c');
Common Scenarios for Array-like Objects
The arguments
Object in Functions
In non-arrow functions, arguments
is an automatically generated array-like object that stores all arguments passed during the function call. Although modern JavaScript recommends using rest parameters (...args
), arguments
still exists in legacy code.
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 6
NodeList
from DOM Operations
NodeList
obtained via document.querySelectorAll
or element.childNodes
is also an array-like object. It supports forEach
(in some environments) but lacks array methods like map
and filter
.
const buttons = document.querySelectorAll('button');
console.log(buttons[0]); // The first button element
console.log(buttons.length); // Number of buttons
Character Access in Strings
Strings can access individual characters via indices, but they are immutable array-like objects.
const str = 'hello';
console.log(str[1]); // 'e'
console.log(str.length); // 5
How to Convert Array-like Objects to Real Arrays
Since array-like objects cannot directly use array methods, they usually need to be converted to real arrays first. Here are some common methods:
Using Array.from()
Array.from()
is the simplest method provided by ES6, supporting array-like objects or iterable objects.
function convertToArray() {
const argsArray = Array.from(arguments);
console.log(argsArray.map(x => x * 2)); // [2, 4, 6]
}
convertToArray(1, 2, 3);
Using the Spread Operator (...
)
The spread operator can expand an iterable array-like object into an array.
const nodeList = document.querySelectorAll('div');
const divArray = [...nodeList]; // Convert to a real array
divArray.forEach(div => console.log(div));
Using Array.prototype.slice.call()
Before ES6, the slice
method combined with call
or apply
was commonly used for conversion.
function oldSchoolConvert() {
const argsArray = Array.prototype.slice.call(arguments);
console.log(argsArray.join('-')); // 'a-b-c'
}
oldSchoolConvert('a', 'b', 'c');
Custom Implementation of Array-like Objects
You can manually create an array-like object by defining indices and a length
property.
const arrayLike = {
0: 'apple',
1: 'banana',
2: 'cherry',
length: 3
};
// Convert to an array
const fruits = Array.from(arrayLike);
console.log(fruits); // ['apple', 'banana', 'cherry']
Limitations of Array-like Objects
Although array-like objects can mimic some array behaviors, they have the following limitations:
- Cannot directly call array methods (e.g.,
push
,splice
); - Certain operations (e.g.,
for...of
iteration) require the object to implement the iterator protocol; - Performance may be lower than native arrays.
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
arrayLike.push('c'); // TypeError: arrayLike.push is not a function
Practical Tips
Borrowing Array Methods
Using call
or apply
, you can temporarily borrow array methods to handle array-like objects.
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
Array.prototype.forEach.call(arrayLike, item => {
console.log(item); // 'a', 'b'
});
Detecting Array-like Objects
You can check if an object is array-like by verifying its length
property (of type number
) and the existence of indices.
function isArrayLike(obj) {
return obj != null
&& typeof obj.length === 'number'
&& obj.length >= 0
&& (obj.length === 0 || (obj.length > 0 && (obj.length - 1) in obj));
}
console.log(isArrayLike({ 0: 'a', length: 1 })); // true
console.log(isArrayLike([])); // true (arrays are also array-like objects)
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn