Javascript Framework Design: Array Extension and restoration of Reading Notes _ javascript skills

Source: Internet
Author: User
This article is the Reading Notes in Chapter 3, Section 2nd of situ's javascript framework design. This section mainly introduces the extension and repair of javascript arrays, this article selects the key parts for demonstration. 1. indexOf and lastIndexOf methods:

Because IE7 reports an error when using indexOf on an array object, you need to override a compatibility.

The Code is as follows:


Array. prototype. lastIndexOf (item, index ){
Var n = this. length, I = (index = null | index> N-1 )? N-1: index;
If (I <0) I = n + I;
For (; I> = 0; I --)
If (this [I] === item) // perform full-level judgment, indexOf, lastIndexOf
Return I;
Return-1;
}

2. shuffle method: shuffling the array.

The Code is as follows:


Function shuffle (target ){
Var I = target. length, j, temp;
For (; I> 0; j = parseInt (Math. random () * I), x = target [-- I], target [I] = target [j], target [j] = x ){}
// Assuming length = 10, then Math. random () * 10-> [), after parseInt, [], randomly select one to exchange with the last entry of the array. The second loop, [0, 8], is exchanged with the second to last entry of the array.
Return target;
}

3. flatten: flatten returns a one-dimensional array.

The Code is as follows:


Function flatten (arr ){
Var result = [];
Arr. forEach (function (item ){
If (Array. isArray (item) result. concat (flatten (item ));
Else result. push (item );
});
Return result;
}

4. unique Method: deduplication of Arrays

This method, the interviewer prefers to ask, because it has multiple implementation methods, the most common is two for loops. It is generally known that the most common thing is to use an object a, and then a for loop array arr, whether the if (a [arr [I]) exists each time, if it does not exist, push it to the newly defined array result. If it exists, it indicates that it is repeated, so you do not need to push it to the result. In this solution, for "123" and 123, it will be considered the same. In fact, one is a string, the other is a number, and should not be considered the same.

So the following method appears: [1, "1", "1"]

The Code is as follows:


If (typeof obj [array [I])! = (Typeof array [I]) | obj [array [I]! = Array [I]) {
A. push (array [I]);
Obj [array [I] = array [I];
}

// First, judge whether the types are the same. If they are the same, judge whether their values are equal. If they are not equal, they are saved. If they are equal, they prove that they already exist.

If the types are different, there are two situations,

In the first case, obj already stores this data, for example, obj [123] = 123, and now array [I] = "123, typeof obj [array [I]) is a number, while typeof array [I] is a string, so it is stored in the array.

The second case is that obj does not store this data, for example, array [I] = "123", obj ["123"] = undefind, in this case, typeof obj [array [I] Is typeof undefined = undefined, which is not equal to typeof array [I] and stored in the array.

This method can solve the problem of the same string and number, but cannot solve the problem of the same object. For example, a = {}, B = };

During the first cycle, typeof obj [a] = undefined, typeof a = Object. Saved to obj [a] = a. Actually it is obj [Object] =;

In the second loop, typeof obj [B] is equal to typeof obj [Object], which is actually typeof a = object, typeof B = object. Therefore, go to obj [array [I]! = Array [I] |, that is, obj [B]-> obj [Object]->! = B, so it is stored

Obj [B] = B; that is, obj [Object] = B; overwrite the previous obj [Object] =;

In this case, all objects will be stored with only the last object value.

When considering objects, I will use the following method:

The Code is as follows:


For (var I = 0; I <temp. length; I ++ ){
For (var j = I + 1; j <temp. length; j ++ ){
If (temp [I] = temp [j]) {
Temp. splice (j, 1 );
J --;
}
}
}
Return temp;

5. array sorting: sort method. if you want to sort objects, you can write a compare (a, B) {if (. age> B. age) return 1; else return-1;},. sort (compare ).

6. min returns the minimum value of the array: return Math. min. apply (0, array );

7. The length of the array is not returned for unshift in ie6 and 7.

The Code is as follows:


If ([]. unshift (1 )! = 1) // Add an item from the front to the empty array. other browsers return 1, while IE6 and 7 do not return the array length. Then the if statement is executed.
{
Var _ unshift = Array. prototype. unshift; // function hijacking.
Array. prototype. unshift = function (){
_ Unshift. apply (this, arguments );
Return this. length;
}
}

8. When a splice parameter is set, the second parameter of IE8 and earlier versions is 0 by default, while other browsers use the array length.

The Code is as follows:


If ([1, 2, 3]. splice (1). length = 0) // IE8 and earlier versions are equal to 0, and other versions are equal to 3. Enter if
{
Var _ splice = Array. prototype. splice;
Array. prototype. splice = function (){
If (arguments. length = 1) // if there is only one parameter
{
Return _ splice. call (this, a, this. length );
} Else {
Return _ splice. apply (this, arguments );
}
}
}

This method will change the options of the array, so the array push, pop, shift, unshift (these methods will also modify the options of the array) will call this method to implement.

Note the following:

The Code is as follows:


Var color = new Array ('red', 'blue', 'yellow', 'black ');
Var color2 = color. splice (2, 0, 'Brown ', 'pink ');
Alert (color); // red, blue, brown, pink, yellow, black, start the operation on the yellow option. If it is deleted as 0, the added option is inserted before yellow. Remember.



Here, let's take a look at the differences between splice and slice, the returned values, and the impact on the original array.

The above is the simplified version of the content in this section. Although it is simplified, it focuses on the content. I hope it will help you read this section.

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.