----arrays from 0 to 1:JAVASCRIPT data structures

Source: Internet
Author: User
Tags javascript array

definition of an array in JavaScript

An array is a special object that is used to indicate that the index of an offset is the property of the object, and the index can be an integer. These numeric indexes are internally converted to string types. this is because the property name in the JavaScript object must be a string. Arrays are a special kind of object in JavaScript and are not efficient in other language arrays.

1.1 How arrays are created
//The following two methods of declaring the array are the sameConsole. log ('-----How arrays are declared-----');varArray1 = [];varArray2 =NewArray ();//Indicate array length when creating an arrayConsole. log ('-----Array length can be specified when creating arrays-----');varArray3 =NewArray (3);Console. log (array3.length); array3[4] =5;Console. log (ARRAY3);//An array that declares a default value, and the elements in the array do not have to be the same type (different from strongly typed languages)Console. log ('-----array of default values-----');varArray4 = [1,' A ',3];varArray5 =NewArray (1,' A ',3);Console. log (Array4);Console. log (Array5);//How to initialize an array by setting the length of the array object to0Console. log ('------Initialize an array----');Console. log (array5); array5.length =0;Console. log (Array5);

Results :

to determine whether a JavaScript array is a method :

//determine if the method is an array  var  array5 =[];console.log (typeof  array5 ==array ); //false  console.log (typeof  array5 ===array ); //false  console.log (typeof  array5); //object  console.log (array . IsArray (Array5)     ); //true  console.log (array5 instanceof  array ); //true   

The typeof operator is not good to know when we want to determine if it is a JS array, you can use the instanceof operator or the built-in function IsArray ()that uses the array object.

1.2 Operations on arrays
var array1 =[1,2,3,4];var array2 = array1;array2[2] =5;console.log(array1);console.log(array2);

Results :

[1, 2, 5, 4]
[1, 2, 5, 4]

It is known from the result that a simple assignment operation is simply called shallow copy (reference replication). deep copy and shallow copy difference click here

A deep copy of an extended array object's own method:

Array.prototype.deepCopy =function(array) {varTemparray = [];//Determine if the array parameter is notNULL,undefined,0,"', Nan,false    if(array) { for(vari =0, Len = array.length;i<len;i++) {Temparray[i] = Array[i]; }returnTemparray; }return NULL;}varArray1 =[1,2,3,4];varArray2 = array1;varArray3 = [];array2[2] =5;Console. log (array1);Console. log (array2); array3 = Array3.deepcopy (array1);Console. log (array3); array3[0] = +;Console. log (array1);Console. log (ARRAY3);

Results :

[1, 2, 5, 4]
[1, 2, 5, 4]
[1, 2, 5, 4]
[1, 2, 5, 4]
[78, 2, 5, 4]

2.1 Finding elements in an array

First throw a "stone", the most common problem of array de-weight:
Code :

varArray1 = [1,2,3,4,5,5,4,2,7,8];Array. prototype. Unrepeat = function(array) {    vartemp = []; for(vari =0, Len =Array. length; i < Len; i++) {if(Temp.length! =0) { for(varm =0; M < temp.length; m++) {varIsexist =false;if(Array[i] = = Temp[m]) {isexist =true; Break; }            }if(Isexist = =false) {Temp.push (Array[i]); }        }Else{Temp.push (Array[i]); }    }returntemp;}

Results :

[1, 2, 3, 4, 5]

The above code can be used to perform the redo operation of the array. However, the time complexity is higher than T (n) = O (n^2) . In fact, in native JavaScript, a method is provided to support the operation of finding elements. indexOf () and lastIndexOf () respectively
Optimized code

Arrayfunction(array) {    var temp = [],        indexResult;    for (var0array.length; i < len; i++) {        indexResult = temp.indexOf(array[i])        if (indexResult == -1null) {            temp.push(array[i]);        }    }    return temp;}

Results :

[1, 2, 3, 4, 5, 7, 8]

The time complexity at this point is T (n) = O (n)

2.2 Sorting of arrays

Look at the code:

var nums = [1,5,9,2,3];//Reverses the elements in the array by Nums.Reverse(); console.Log(Nums);//Can be used when an array element is a stringSort() var strarray = [' Qwe ',' Erere ',' SDSF ',' Hghgj '];strarray.Sort(); console.Log(Strarray);//The numbers areSort() method var numarray = [1, $, the, at, 09, -];numarray.Sort(); console.Log(Numarray);

The results are as follows:

[3, 2, 9, 5, 1]
[' Erere ', ' hghgj ', ' qwe ', ' SDSF ']
[1, 100, 23, 45, 67, 9]

It is clear that it is not effective to use the sort () method to sort arrays when the elements of the array are numbers. What is this for?

the sort () method is sorted in dictionary order. So when you use the sort () method, the sorted elements are sorted directly in the dictionary order if they are not numbers. If a number is internally converted, the number is converted to a string.
In order for the sort () method to be able to sort the numeric elements, you can pass in the sort () method to a larger function. Sort () determines the size of the element based on the function and determines the order of the array.

Look at the following section of code:

//对数字进行sort()方法var numArray = [1,45,67,23,09,100];numArray.sort();console.log(numArray);function sortNum(num1,num2){    //减号操作符会将两边的字符串强制转换为数字    return num1 - num2;}numArray.sort(sortNum);console.log(numArray);

The result is:

[1, 9, 23, 45, 67, 100]

3.1 iterator method for arrays3.1.1 Iterator method that does not generate a new array

ForEach () This method takes a function parameter and applies the function to all elements of the array

var numArray = [1,45,67,23,09,100];function eachFunc(num){    ‘字符串‘);}numArray.forEach(eachFunc);console.log(numArray);

Results:

1 string
9 string
23 string
45 string
67 string
100 string
[1, 9, 23, 45, 67, 100]

Defined:

The Every () and some () methods accept a function that returns a Boolean type that uses the function for elements in the array. If for all elements. The return value of the function is true, the method returns True.

The code is as follows:

varNumarray = [1, $, the, at, the, -];varNumArray1 = [-1, $, the, at, the, -]; function evefunc(num) {    returnnum >0;} function resultfunct(Result) {    if(Result) {Console.log (' All is positive. '); }Else{Console.log (' a negative number exists. '); }}varresult = Numarray.every (Evefunc); resultfunct (result);varRESULT1 = Numarray1.every (Evefunc); resultfunct (RESULT1);

Results:

All are positive.
A negative number exists.

3.1.2 Iterator method for generating a new array

Map () and filter () apply the function to each element of the array. But map () returns a new array.
The filter () function is similar to the every () function, and the Every () function returns True when all elements satisfy a condition, and the filter () function returns a new array.

function mapFunc(num){    return num *2;}var numArray1 = [-145672309100];var resultMap = numArray1.map(mapFunc);console.log(resultMap);

Results:

[-2, 90, 134, 46, 18, 200]

----arrays from 0 to 1:JAVASCRIPT data structures

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.