Time Date and array Array_javascript techniques for javascript reference types

Source: Internet
Author: User
Tags month name
The value (object) of the reference type is actually an instance of the reference type. Next, we will introduce the Date of the javascript reference type and the Array through this article, for more information about the Javascript reference type, see Date.


The Date type in JavaScript is built on the Java. util. Date class in early java. Therefore, the Date type uses the number of milliseconds since UTC January 1, January 1, 1970 to save the Date. When this data storage format is used, the Date type can be accurate to January 1, 1970, January 1, 285, or later, before or after January 1, 616.

Creation date object

In javascript, you can use the Date () constructor to create a Date object, for example:


The Code is as follows:


Var date = new Date ();


If the date parameter is not passed to the constructor, an object with the current date and time is created.

Of course, if you want to create a date object based on a specific date and time, you only need to pass the parameter that can represent the date into the constructor.

The Date () constructor can accept the following common Date formats:

"Month/day/Year", for example, 2/27/2014;
"English month name day, year", such as February 27,2014;
"Year, month, day, hour, minute, second, millisecond", such

Create a date object in the preceding format:


var date1=new Date("2/27/2014"); 
alert(date1); //Thu Feb 27 2014 00:00:00 GMT+0800
var date2=new Date("February 27,2014");
alert(date2); //Thu Feb 27 2014 00:00:00 GMT+0800
var date3=new Date(2014,1,27,11,24,0);
alert(date3); //Thu Feb 27 2014 11:24:00 GMT+0800
var date4=new Date(2014,1,27);
alert(date4); //Thu Feb 27 2014 00:00:00 GMT+0800
var date5=new Date("2014,1,27,11,24,0");
alert(date5); //Invalid Date


Through the above example, you may notice the differences between them:

First, when you create a date object in the preceding two methods, the object must be input as a string. However, when you create a date object in the third method, the object cannot be input as a string, each value must be passed in as a separate value.

Second, you must pay special attention to the fact that when you create a date in the third method, its month starts from 0, that is, the month corresponding to 0 in January, and so on; the first two methods are normal month representation, that is, February corresponds to 2.

Third, the year and month are required when the third method is used. If other parameters are omitted, the value is 0.
Note: The preceding two methods are consistent with the displayed method of calling the Date. parse () method. The third method is consistent with the displayed method of calling the Date. UTC () method.

Inheritance Method

The Date type also inherits the toString (), toLocaleString (), and valueOf () methods. The format of the values obtained by calling these methods varies with the browser. Specifically, you can try to call it.

Date formatting Method

The Date type also has some special methods used to format the Date as a string, as follows:

ToDateString () -- display the day of the week, month, day, and year in a specific and implemented format;

ToTimeString () -- display time, minute, second, and time zone in a specific format;

ToLocaleDateString () -- display the day, month, day, and year of the week in the region-specific format;

ToLocaleTimeString () -- display time, minute, and second in a realistic format;

ToUTCString () -- display the complete UTC date in a specific display format

The above methods may not be frequently used, so we will not discuss them in detail.

Date/time component method


Array of Javascript reference types


[22 Methods of array overview]

Arrays in javaScript are quite different from arrays in most other languages. Although JavaScript arrays and arrays in other languages are ordered lists of data, different from other languages, each item of JavaScript Arrays can maintain any type of data. That is to say, you can use the first position of the array to save the string, the second position to save the value, and the third position to save the object. In addition, the size of the JavaScript array can be dynamically adjusted, that is, it can automatically increase as data is added to accommodate new data.

Array: each item in the Array can save any type of data, and the Array size is dynamically adjusted (up to 4294967295 items, about 4.3 billion items)

[1.1] array creation:

[1.1.1] Use Array Constructor (when using Array constructor, the New operator can also be omitted)


e.g. var colors = new Array();
var colors = new Array(20);
var colors = new Array('red','blue','green');
var colors = Array(3);


[Note] If a value is passed, an array containing the specified number of items is created based on the value;

If other types of parameters are passed, an array containing only one item is created.


e.g. var colors = new Array (3); // An array containing three items
var colors = new Array ('Greg'); // An array containing one item, and the item is "Greg"


[1.1.2] Array literal representation (this method does not call the Array constructor)


e.g. var colors = ['red', 'blue', 'green'];
var colors = [];
[Not available] var colors = [1,2,];


// In IE8 and before, there will be an array of three projects, each of which is 1, 2, and undefined. In other browsers, add an array containing only 1 and 2.

[Unavailable] var colors = [,];

// Four arrays will be created in IE8 and before, and three arrays will be created in other browsers

[1.2] array read/write

[1.2.1] when reading and setting array values, square brackets should be used and a 0-based numeric index should be provided for the corresponding values. The number of array items should be stored in its length attribute, this attribute always returns 0 or a greater value.

[1.2.2] The length attribute of an array can be read and written. By setting the Length attribute of an array, you can remove items from the end of the array or add new items to the array.


e.g. var colors = ['red','blue','green'];
colors.length = 2;
alert(colors[2]);//undefined
colors.length = 4;
alert(colors[3]);//undefined


[1.2.3] using the length attribute, you can easily add new items to the end of the array.


e.g. colors[colors.length] = 'black';


[1.2.4] When a value is placed above the array size, the array recalculates its length value, that is, the length value equals to the index of the last item and Adds 1.


e.g. var colors = ['red','blue','green'];
colors[99] = 'black';
alert(colors.length);//100 


[1.3] array detection

[1.3.1] if (value instanceof Array) {}: the problem is that it assumes that there is only one global execution environment. if the webpage contains multiple frameworks, there are actually two or more different global environments, so there are two or more different versions of the Array constructor. If an array is imported from one framework to another, the input array and the array originally created in the second framework have different constructors respectively.

[1.3.2] ECMAScript5 adds the Array. isArray () method: if (Array. isArray (value )){}. The purpose of this method is to determine whether a value is an array or not, regardless of the global environment in which it creates

[1.4] array Conversion

[Note] if the value of an item in the array is null or undefined, the value is expressed as an empty string in the results returned by the join (), toLocaleString (), toString (), and valueOf () methods.

[1.4.1] toString (): returns a comma-separated string consisting of strings of each value in the array.

[1.4.2] valueof (): returns an array.


e.g. var colors = ['red','blue','green'];     
console.log(colors.valueOf());//['red','blue','green']
alert(colors.valueOf());//'red,blue,green'
alert(colors.toString());//'red,blue,green'
alert(colors);//'red,blue,green'


[Note] Because alert () needs to receive string parameters, it will call the toString () method in the background and get the same result as the toString () method.

[1.4.3] toLocaleString (): it creates an array value that is separated by commas (,), and each value calls the toLocaleString () method.


var person1 = {
 toLocaleString: function(){
 return 'Nikolaos';
 },
 toString: function(){
 return 'Nicholas';
 }
};
var person2 = {
 toLocaleString: function(){
 return 'Grigorios';
 },
 toString: function(){
 return 'Greg';
 }
};
var people = [person1,person2];
alert(people);//Nicholas,Greg
alert(people.toString());//Nicholas,Greg
alert(people.toLocaleString());//Nikolaos,Grigorios


[1.4.4] join: You can use different delimiters to construct this string. join only receives one character and serves as the separator. Then, it returns a string containing all array items.


e.g. var colors = ['red','green','blue'];
alert(colors.join(','));//'red,green,blue'
alert(colors.join('||'));//'red||green||blue'
alert(colors.join());//'red,green,blue'
alert(colors.join(undefined));//'red,green,blue'


[Note] In IE7 and earlier, undefined will be used as the Separator

[1.5] Array Method

[1.5.1] stack method: Stack is a kind of LIFO (last-in-first-out), first-in-first-out data structure, that is, newly added items are first removed. The insertion (push) and removal (pop-up) of items in the stack only occur at the top of the stack.

[1.5.1.1] push () method: You can receive any number of parameters, add them one by one to the end of the array, and return the length of the modified array.

[1.5.1.2] pop () method: remove the last item from the end of the array, reduce the length value of the array, and return the removed item.

[1.5.2] queue method: a FIFO (first-in-first-out) data structure. A queue is added at the end of the list, remove items from the front-end of the list.

[1.5.2.1] shift (): removes the first entry in the array and returns this item. At the same time, the length of the array is reduced by 1 (the queue can be simulated by using shift () and push)

[1.5.2.2] unshift (): Add any item on the front end of the array and return the length of the new array (use unshift () and pop () to simulate the queue in the opposite direction)

[Note] IE7 and the following unshift () methods always return undefined

[1.5.3] sorting method:

[1.5.3.1] reverse (): returns the sorted array in reverse order.

[1.5.3.2] sort (): sorts array items in ascending order. The sort method calls the toString () method of each array item, sorts the obtained strings, and returns the sorted array.

[Note] the sort () method can take a comparison function as a parameter to specify the value before which. The comparison function receives two parameters. If the first parameter is located before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is located after the second parameter, a positive number is returned.

[Comparison function] (Use: e.g. array1.sort (compare );)


function compare(value1,value2){
 if(value1 < value2){
 return -1;
 }else if(value1 > value2){
 return 1;
 }else{
 return 0;
 }
}
 

The value type or valueOf () method returns the object type of the value type. The comparison function can be simplified:


function compare(value1,value2){
return value2 - value1;
}


[Tips]: Use the following methods to create a random array:


function compare(){
return Math.random() - 0.5;
}


[1.5.4] operation method (CUT, connect, insert, delete, and replace ):

[1.5.4.1] concat (): Creates a new array based on all items in the current array, creates a copy of the current array, and then adds the received parameters to the end of the copy, finally, the newly constructed array (concat () does not affect the original array) is returned)

[NOTE 1] When a parameter is not passed to the concat () method, It just copies the current array

[NOTE 2] If the parameter is one or more arrays, this method adds each of these arrays to the result array.

[NOTE 3] If the passed values are not arrays, these values will be simply added to the end of the result array.


e.g. var numbers = [1,2];
console.log(numbers.concat());//[1,2]
console.log(numbers.concat([5,4,3],[3,4,5],1,2));//[1,2,5,4,3,3,4,5,1,2];


[1.5.4.2] slice (): Creates a new array based on one or more items in the current array and accepts one or two parameters, that is, the start and end positions of the items to be returned, finally, the new array (slice () does not affect the original array) is returned)

[NOTE 1] If no parameter exists, the original array is returned.

[NOTE 2] when there is only one parameter, the slice () method returns all items starting from the specified position of this parameter to the end of the current array.

[NOTE 3] When two parameters are specified, this method returns an item between the start position and the end position, but does not include an item at the end position.

[NOTE 4] If the parameter is a negative number, the array Length plus a negative number is used as the parameter.

[Note 5] If the end position is less than the start position, an empty array is returned.


var numbers = [1,2,3,4,5];
console.log(numbers.slice());//[1,2,3,4,5]
console.log(numbers.slice(2));//[3,4,5]
console.log(numbers.slice(2,3));//[3]
console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]
console.log(numbers.slice(2,1));//[]


[1.5.4.3] splice (): The original array is changed to the modified array, and splice () returns an array composed of items deleted from the original array. If no items are deleted, an empty array is returned.

[A] Delete: the two parameters are the location of the first item to be deleted and the number of items to be deleted.

[B] Insert: the three parameters are start position, 0 (base number to be deleted), and the items to be inserted.

[C] replacement: the three parameters are the starting position, number of items to be deleted, and items to be inserted.

[NOTE 1] if the first parameter is negative, the array length and negative number are used as parameters.

[NOTE 2] If the second parameter is negative, 0 is used as the parameter.


var numbers = [1,2,3,4,5];
    console.log(numbers.splice(0,2),numbers);//[1,2] [3,4,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(1,0,11,12),numbers);//[] [1,11,12,2,3,4,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(1,3,11,12),numbers);//[2,3,4] [1,11,12,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(-4,3,11,12),numbers);//-4+5=1 -> [2,3,4] [1,11,12,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(-4,-3,11,12),numbers);//-4+5=1 -> [] [1,11,12,2,3,4,5]


[1.5.5] Location Method (ECMAScript5): two parameters: the item to be searched and the index indicating the start position (optional ). Returns the position of the first search item that meets the condition in the array. If no position is found,-1 is returned (the position method does not affect the original array)

[Note] the full operator is used for comparison.

[1.5.5.1] indexOf ()

[1.5.5.2] lastIndexOf ()


var person = {name: 'Nicholas'};
var people = [{name: 'Nicholas'}];
var morePeople = [person];
alert (people.indexOf (person)); //-1, because person and people [0] have the same value, but they are two references
alert (morePeople.indexOf (person)); // 0, because person and morepeople [0] are the same reference
alert (morePeople.indexOf ((name: 'Nicholas'))); //-1, because it is not the same reference


[Tips] If all index values of the items that meet the conditions are returned


function allIndexOf(array,value){
 var result = [];
 var pos = array.indexOf(value);
 if(pos === -1){
  return -1;
 }
 while(pos > -1){
  result.push(pos);
  pos = array.indexOf(value,pos+1);
 }
 return result;
  }
 var array = [1,2,3,3,2,1];
 console.log(allIndexOf(array,1));//[0,5]  


[1.5.6] iteration method (ECMAScript5): two parameters: the function to be run on each item, and the function scope object to be run -- the value that affects this (optional ). The function passed in these methods will receive three parameters: the value of the array item, the position of the item in the array, and the array object itself (the iteration method will not affect the original array)

[1.5.6.1] every (): run the given function for each item in the array. If this function returns true for each item, true is returned.

[1.5.6.2] filter (): If you run a given function for each item in the array, returning this function returns an array consisting of true items (usually used to query all array items that meet the conditions)

[1.5.6.3] forEach (): This method does not return a value (equivalent to a for loop) for running a given function for each item in the array)

[1.5.6.4] map (): returns an array composed of the results of each function call to run a given function for each item in the array (usually used to create an array with one-to-one correspondence between the contained item and another array)

[1.5.6.5] some (): run the given function for each item in the array. If this function returns true for any item, true is returned.


 var numbers = [1,2,3,4,5,6,7,8,9,0];
 var sum = 0;
 var everyResult = numbers.every(function(item,index,array){
  return (item>2);
 });
 var filterResult = numbers.filter(function(item,index,array){
  return (item>2)
 });
 var forEachResult = numbers.forEach(function(item,index,array){
  sum += item;
  return (item>2)
 });
 var mapResult = numbers.map(function(item,index,array){
  return (item*2)
 }); 
 var som =  numbers.some(function(item,index,array){
  return (item>2)
 }); 
 console.log(everyResult);//false
 console.log(filterResult);//[3,4,5,6,7,8,9]
 console.log(forEachResult,sum);//undefined 45 
 console.log(mapResult);//[2,4,6,8,10,12,14,16,18,0]
 console.log(someResult);//true
 [tips] function logArray(value,index,array){
   console.log(value);
  }
  [2,5,,,,,9].forEach(logArray)//2 5 9


[1.5.7] The merge method (ECMAScript5) is used to iterate all the items in the array and construct a final returned value. Receive two parameters: a function called on each item and an initial value as the basis for merging (optional ). The function passed to reduce () and reduceRight () accepts four parameters: the index of the previous value, current value, and item, and the array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs in the second entry of the array. Therefore, the first parameter is the first item of the array, and the second parameter is the second item of the array (the merging method does not affect the original array)

[1.5.7.1] reduce ()

[1.5.7.2] reduceRight ()


var sum = values.reduce(function(prev,cur,index,array){
    return prev+cur;
   })
   alert(sum);//15

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.