The difference between an array in JavaScript and a pseudo-array

Source: Internet
Author: User
Tags object object

In JavaScript, all but 5 of the original data types are objects, including functions.

5 Types of raw data:

    • Number

    • Boolean

    • String

    • Null

    • Undefined

In this context, let's talk about JavaScript objects.

1. Create objects
var obj = {}; A way of creating an object, called the object Direct amount (object Literal) var obj = new Object (); Create an empty object, as with {}

For more knowledge of creating objects, see the JavaScript Authoritative Guide (6th edition), chapter 6th

2. Creating an array

var arr = [];//This is to use array direct amount (array Literal) to create an array of var arr = new Array ();//constructor Array () to create arrays of objects

For more knowledge of creating arrays, see Chapter 7th of the JavaScript Authoritative Guide (6th edition).

3. The relationship between an object and an array

Before you tell the difference, you need to mention another knowledge, that is, JavaScript's prototype inheritance. All JavaScript built-in constructors are inherited from Object.prototype. In this context, it can be understood that array objects created using the new array () or [] will have Object.prototype property values.

The problem with the main question means:

var obj = {};//owns Object.prototype property value var arr = [];//array created using array direct amount, because Array.prototype properties inherit from object.prototype,//then, It will have both Array.prototype and Object.prototype property values.

You can get the first difference between an object and an array: The object does not have a property value for the Array.prototype

4. What is an array

The array has one of the most basic characteristics: The index, which is not what the object is, and here's a code:

var obj = {};var arr = [];obj[2] = ' a '; arr[2] = ' a '; Console.log (obj[2]); Output Aconsole.log (arr[2]); Output Aconsole.log (obj.length); Output Undefinedconsole.log (arr.length); Output 3

From the above test, you can see that although obj[2] and arr[2] Both output ' a ', but there is a significant difference in the output length, which is why?

The difference between obj[2] and arr[2]

    • OBJ[2] Output ' a ' because the object is an ordinary key-value pair accessing data

    • ARR[2] Output ' A ' is different, the array is indexed to access the data, arr[2] output ' a ' because the location of the array Arr index 2 has stored the data

The difference between Obj.length and arr.length

    • Obj.length does not have an array attribute, and obj does not save the property length, then it will naturally output undefined

    • For arrays, length is a built-in property of an array, and the array changes the value of length based on the length of the index.

Why Arr.length Output 3 instead of 1?

    • This is due to the special implementation mechanism of the array, for the normal array, if its index is starting from 0 consecutive, then the value of length will be equal to the number of elements in the array

    • For ARR in the example above, when adding elements to an array, it is not added as successive indexes, so the index of the array is not contiguous, so the index length is greater than the number of elements, then we call it a sparse array.

The features of sparse arrays are no longer discussed in more detail, see the JavaScript Authoritative Guide (6th edition), section 7.3.

5. Pseudo-Array

Defined:

1, has the length property, the other attribute (index) is a nonnegative integer (the index in the object will be treated as a string, here you can think of as a non-negative integer string to understand)
2, does not have the method that the array has

Pseudo-arrays, which have properties like arrays, have,,,, and so on, length 0 1 2 3 look like arrays, but not arrays, such as

var Fakearray = {    length:3,    "0": "First",    "1": "Second",    "2": "Third"};for (var i = 0; i < FAKEARRAY.L Ength; i++) {    console.log (fakearray[i]);} Array.prototype.join.call (Fakearray, ' + ');

The parameters of the common parameters arguments,dom the object list (such as the list obtained by Document.getelementsbytags), JQuery objects (such as $ ("div")).

A pseudo-array is an Object, and a real array is a

Fakearray instanceof Array = = = False;object.prototype.tostring.call (fakearray) = = = "[Object Object]"; var arr = [ 1,2,3,4,6];arr instanceof Array = = = True;object.prototype.tostring.call (arr) = = = "[Object Array]"

The

JavaScript authoritative guide gives code to determine whether an object belongs to an "array of classes." as follows:

//determine if O is an array-like object.//Strings and functions has numeric length Properties, but is//excluded by the TypeOf test. In Client-side JavaScript, DOM text//nodes has a numeric length property, and could need to being excluded//with an additio NAL O.nodetype! = 3 test.function isarraylike (o) {if (o &&//O is not NULL, UN        Defined, etc. typeof o = = = ' object ' &&//O is an object Isfinite (o.length) &&//O.leng Th is a finite number o.length >= 0 &&//o.length are non-negative o.length=== Math.floor (o.length) &&//O.length is an integer o.length < 4294967296)//O.length <                        2^32 return true;                       Then O is Array-likeelse return false; Otherwise it is not} 

But there's an easier way to judge, withArray.isArray

Array.isarray (fakearray) = = = FALSE; Array.isarray (arr) = = = true;

Look at the pseudo-array from the appearance, do not see it and the array of differences, in JavaScript built-in objects common pseudo-array is the famous auguments:

(function () {  console.log (typeof arguments);//Output object, which is not an array} ());

In addition, in DOM objects, ChildNodes is also a pseudo-array

Console.log (typeof Document.body.childNodes); Output Object

In addition, there are many common pseudo-arrays, not listed.

The meaning of pseudo-arrays is that there are many algorithms that allow normal objects to work with arrays, such as:

var arr = Array.prototype.slice.call (arguments) or var arr = Array.prototype.slice.call (arguments, 0); Converts the arguments object to a true array Array.prototype.forEach.call (arguments, function (v) {  //Loop arguments object});

In addition to using Array.prototype.slice.call (arguments), you can also simply use [].slice.call (arguments) instead. In addition, you can use bind to simplify the process.

var unboundslice = Array.prototype.slice;var slice = Function.prototype.call.bind (unboundslice); Function list () {  return slice (arguments);} var list1 = list (1, 2, 3); [1, 2, 3]

Converts an object with the length property to an array of objects, arguments is an approximation of the object that each function automatically obtains at run time (the parameters passed in the function are numbered from 0 and have length).

For example, when you func (' A ', ' B ', ' C '), the arguments[0 obtained in Func is ' a ', arguments[1] is ' B ', and so on. But the problem is that this arguments object is not an array, so there is no slice method. Array.prototype.slice.call () can indirectly implement the slice effect on it, and the result returned is a true array.

For the previous version of IE9 (the DOM implementation is COM-based), we can use Makearray to implement it.

Pseudo-array conversions var makearray = function (obj) {    if (!obj | | obj.length = = 0) {        return [];}    Non-pseudo class object, directly returning the best if (!obj.length) {        return obj;}    The COM implementation of the previous DOM for IE8 try {        return [].slice.call (obj);} catch (e) {        var i = 0,    j = obj.length,    res = [];
   for (; i < J; i++) {Res.push (obj[i]);} return res;}};

For more information on pseudo-arrays, see the JavaScript Authoritative Guide (6th edition), section 7.11.

6. Summary
    • The Array.prototype object does not have an array of property values, the type is object, and the array type is a;

    • An array is an index-based implementation, and length is automatically updated, and the object is a key-value pair;

    • Using objects can create pseudo-arrays, and pseudo-arrays can normally use most of the methods of arrays;

The difference between an array in JavaScript and a pseudo-array

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.