How to Apply objects and arrays in javascript _ basic knowledge

Source: Internet
Author: User
Javascript has been using objects and arrays in javascript for more than three years, but it still has some details, such as objects and arrays, some basic operations are always used. This is a bad habit for me to learn-lazy. Many things only know about it, and there is no patience to see the logic that is a little complicated. Just like learning asp, I don't know the relationship between asp and script, and learning html doesn't know what DOM is... the result is that the learning process is slow and not solid. When you encounter a complicated problem, you can take a rest ).
Today, I continued to optimize the script. I tried to merge some arrays and encountered problems, so I carefully read the manual and did some tests.

After javascript1.2, you can use [] to create an array:


Var firstArray = [];
Var secondArray = ["red", "green", "blue"];
Var thirdArray = [,];

You can add elements after creating an array:

SecondArray [4] = 28;

The result is that there is an empty Element Between 4th elements and 2nd elements.
The result is similar to this: ["red", "green", "blue", 28]
Note that the array must be initialized. I tested the definition of the array as an array element:

Var arrArray = [[];

We designed to implement a two-dimensional array. The result is that arrArray [I] [0] is invalid when I> 0!
After taking a closer look, we can see that arrArray [0] is defined as an empty array, and other elements are not defined, which is equivalent
Var arrArray = [];
ArrArray [0] = [];
Therefore, arrArray [1] is not defined, so an error occurs when you operate it as an array.

Delete an array element: delete



Var myColors = ["red", "green", "blue"];
Delete myColors [1];
Alert ("The value of myColors [1] is:" + myColors [1]);

The delete result is myColors [1] = undefined, but myColors. length remains unchanged. myColors becomes like this: ["red", "blue"]

Use slice () to replace or absolutely Delete array elements ():


Var myArray = [1, 2, 3, 4, 5];
MyArray. slice (2); // returns [3, 4, 5]
MyArray. slice (1, 3); // returns [2, 3]
MyArray. slice (-3); // returns [3, 4, 5]
MyArray. slice (-3,-1); // returns [3, 4]
MyArray. slice (-4, 3); // returns [2, 3]
MyArray. slice (3, 1); // returns []

Var myArray = [1, 2, 3, 4, 5];
MyArray. splice (3, 2, ''a', ''B '');
// Returns [, 3, ''a', ''B ']
MyArray. splice (1, 1, "in", "the", "middle ");
// Returns 2 [1, "in", "the", "middle", 3, ''a', ''B ']


Only after reading the document can we know that the array is passed for reference!


Var x = [10, 9, 8];
Var y = x;
X [0] = 2;
Alert ("The value of y's first element is:" + y [0]);

Guess what the result is?
Let's look at this again:

// Declare a reference type (array)
Var refType = ["first", "second", "third"];

// Declare a primitive type (number)
Var primType = 10;

// Declare a function taking two arguments, which it will modify
Function modifyValues (ref, prim)
{
Ref [0] = "changed"; // modify the first argument, an array
Prim = prim-8; // modify the second, a number
}

// Invoke the function
ModifyValues (refType, primType );
// Print the value of the reference type
Document. writeln ("The value of refType is:", refType + "<
> ");
// Print the value of the primitive type
Document. writeln ("The value of primType is:", primType );


A problem found during the test:


Var arr = [];
Arr ['a'] = 1;
Arr ['B'] = 2;
Alert (arr. length );

The displayed number is 0!
After reading the document, we can see that such an array is called the Associative Arrays. arr ['a'] is equivalent to arr. a, arr. length is equivalent to arr ['length'], and arr. length is automatically assigned 0 when we initialize arr (var arr =.
Someone calls this federated array a javascript hash table. Strictly speaking, the Union array and the ordinary array are both objects (nonsense, everything in javascript is an object--), meaning and usage are the same. See the following example:

Var arr = [];
Arr = [1, 2, 3];
Arr. test = 'test ';
Alert (arr );
Alert (arr [1]);
Alert (arr ['test']);

Var arr = {}; arr = [2, 3, 4]; alert (arr [0]);
Var arr ={}; and var arr = [] can both be written as var arr = function (){};
From the code above, we can see that the subscript array is independent from the Union array. The subscript only acts on the subscript array and cannot access the Union array. Correspondingly, the Union array does not affect the length attribute. The tag of the combined array is an attribute, but the subscript of the subscript array is not an attribute. arr [0]! = Arr.0. An error occurs when you access arr.0.

In some cases, arr ['a'] is used to replace arr. a is more effective as a method call, because 'A' in arr ['a'] can be passed in using variables, such as assigning a method to a variable:


Var d = document, l = links;

At this time, direct d. l will cause errors, and use d [l] to execute the statements correctly. alert will know at a moment :)

Alert (d. l); // Script Error
Alert (d [l]); // displays the object

Since an array is an object with the lenght attribute, is it an array for all objects with the length attribute? For example, String. After testing, firefox can treat String as an array, but ie cannot:


Var myString = "Hello world ";
Alert (myString. length );
Alert (myString [0]);

Array objects should be unique, and user objects cannot be completely simulated:



Function myarray (size ){
This. length = size;
Var x = 0;
}
Var arr = new myarray (5 );
Arr [9] = 1;
Alert (arr );
Alert (arr [9]);
Alert (arr. length );

In this case, the length attribute of the Array is a common object attribute. The results show that the length of the arr is no longer an Array length, and the structure of the arr is not a common Array structure.

There are several methods for defining a function/class:


Function fName (arguments ){
// Function body
};

Var fName = function (arguments ){
// Function body
}

Var fName = new Function ("arguments", "/* function body */");


The third method is more fun. See the following example:

Var arr = new Function ("var total = 0; for (var I = 0; I

This method can be used to parse the JSON returned by ajax, so that no inefficient eval is needed (no test is performed to determine whether it is faster than eval ):
Suppose {B: {c: 2} is the returned json string:


Var arr = new Function ("this. a = {B: {c: 2 }};");
Var aa = new arr ();
Alert (aa. a. B. c );

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.