Home >Web Front-end >JS Tutorial >Introduction to array-like objects in JavaScript_javascript skills

Introduction to array-like objects in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:29912browse

In JavaScript, an array is a special object whose property name is a positive integer, and its length property changes as the array members increase or decrease. At the same time, it inherits some parameters from the Array constructor for array processing. Method of operation. For an ordinary object, if all its property names are positive integers and have corresponding length properties, then although the object is not created by the Array constructor, it still exhibits the behavior of an array. In this case, these objects are called "array-like objects". The following is a simple array-like object:

Copy code The code is as follows:

var o = {0:42, 1:52, 2:63, length:3}
console.log(o);

Different from ordinary objects, array-like objects have a feature: array operation methods can be applied to array-like objects. For example, in the ECMAScript 5 standard, the following method can be used to merge the above object o into a string:
Copy code The code is as follows:

console.log(Array.prototype.join.call(o));//"42,52,63"

You can also use the slice() method on an array-like object to obtain a subarray:
Copy code The code is as follows:

console.log(Array.prototype.slice.call(o, 1, 2));//[52]

In a browser environment, the document.getElementsByTagName() statement returns an array-like object. In a function call, the arguments variable within the function code (which holds the passed-in parameters) is also an array-like object.

In the ECMAScript 5 standard, the string string is a read-only array-like object:

Copy code The code is as follows:

var s = "History";
console.log(s[3]);//t
console.log(Array.prototype.join.call(s, " "));//H i s t o r y
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