JavaScript type System Array Object learning notes _javascript Tips

Source: Internet
Author: User
Tags array length numeric value

An array is a sequence of values, in contrast, the object's property name is unordered. In essence, arrays use numbers as lookup keys, while objects have user-defined property names. JavaScript does not have a true associative array, but the object can be used to implement the associated functionality

Array () is just a special type of object (), that is, the array () instance is essentially an object () instance that has some extra functionality. Arrays can hold values of any type that can be updated or deleted at any time, and the size of the array is dynamically adjusted

One, array creation

As with most objects in JavaScript, you can use the new operator with the array () constructor, or by using literal syntax to create an array object

"1" uses the array constructor (you can also omit the new operator when you use the array constructor) to pass the value of the array instance to the constructor, separated by commas as arguments, and the array () constructor can receive 4294967295 (about 4.3 billion) parameters

If there is only one argument: if you pass a numeric value, it is used to set the length of the array, and if you pass other types of arguments, you create an array of only one that contains that value.

var colors;
Console.log (colors = new Array (), colors.length),//[] 0
console.log (colors = new Array (' Red ', ' blue ', ' green '), colors.length);//[' Red ', ' blue ', ' green '] 3
console.log (colors = new Array, colors.length);//[]
Console.log (colors = new Array (' Red '), colors.length);//[' Red ' 1
var foo = new Array (1,2,3);
var bar = new Array (m);
Console.log (foo[0],foo[2]);//1 3
Console.log (bar[0],bar.length);//undefined 100

"2" uses an array literal notation

var colors = [' Red ', ' blue ', ' green '];
var colors = [];



Array constructor
var myArray1 = new Array (' Blue ', ' green ', ' orange ', ' red ');
Console.log (myArray1);//[' Blue ', ' green ', ' orange ', ' red ']
//array literal notation
var myArray2 = [' Blue ', ' green ', ' Orange ', ' Red '];
Console.log (myArray2);//[' Blue ', ' green ', ' orange ', ' red ']



var colors = [1,2,]; 
There are three items in IE8 and before, and each item is an array of 1, 2, and undefined. In other browsers for arrays containing only 1 and 2
var colors = [,,,];
 An array of 4 items is created in IE8 and previously, and 3 items are created in other browsers 

Two, array operation

A 0-based numeric index that uses square brackets and provides values when reading and setting the values of an array

The length property of the array represents the number of values in the array, and the numeric index of the array starts at 0, and the length property is readable and writable, by setting the length property of the array, you can remove the item from the end of the array, or add a new item to the array. If the length of the set is higher than the actual number of values in the array, the undefined value is added to the array, and if the number of length values is set to less than the number of values in the array, the values in the array may be deleted

var myarray = [' Blue ', ' green ', ' orange ', ' Red '];
Console.log (myarray.length);//4
myarray.length =
; Console.log (myarray.length);//99
myarray.length = 1;
Console.log (myarray[1]);//undefined
Console.log (myarray);//[' Blue ']

 

var colors = [' Red ', ' blue ', ' green '];
Colors.length = 2;
Alert (colors[2]);//undefined
colors.length = 4;
Alert (colors[3]);//undefined

When you place a value above the size of the array, the array recalculates its length value, that is, the index of the last item with the length value plus 1,javascript will populate all indexes before the current index with the undefined value

var myarray = [];
MYARRAY[50] = ' blue ';
Console.log (myarray.length);//51
var colors = [' Red ', ' blue ', ' green '];
COLORS[99] = ' black ';
Console.log (colors.length);//100  

[Tips] Use the Length property to easily add new items to the end of the array

colors[colors.length] = ' black ';

Iii. Methods of Inheritance

ToString ()

Returns a comma-delimited string of strings for each value in the array

ValueOf ()

Returns an array of

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 () to receive string parameters, It calls the ToString () method in the background and gets the same result as the ToString () method

toLocaleString ()

When this method is invoked, the value of each item in the array is called 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

Iv. Example Methods

Array conversions
join ()

Array Inherits toLocaleString (), toString (), valueof () methods, which return array entries by default as comma-delimited characters, while the join () method constructs the string using a different delimiter, join () method receives only one argument, a string that is used as a delimiter, and then returns a string that contains all the array items. If you do not pass in any values to the join () method, or if you pass in undefined, use a comma as the delimiter

var colors = [' red ', ' green ', ' Blue '];
Console.log (Colors.join (', '));//' Red,green,blue '
console.log (colors.join (' | | | ')); /' red| | green| | Blue '
Console.log (Colors.join ());//' Red,green,blue '
console.log (colors.join (undefined));//' Red,green, Blue ' [Note that]ie7-will use undefined as a separator

[note] If the value of an item in an array is null or undefined, the value is represented in an empty string in the result returned by the join (), tolocalestring (), toString (), and valueof () methods

Array detection
since ES3, there has been a classic problem of determining whether an object is an array. A common method is to use the instance operator, but the method has its limitations; ES5 specifically added a IsArray () method to detect arrays

var value = [123];
Console.log (value instanceof Array);//true

The problem with the instanceof operator is that it assumes that there is only one global execution environment, and if the Web page contains more than one frame, there are actually more than two different global environments in which there are more than two different versions of the array constructor. If you pass an array to another frame from one frame, the passed-in array has its own different constructors than the array created in the second frame

 Cannot share prototype attribute in different frames
var iframe = document.createelement (' iframe ');
Document.body.appendChild (IFRAME);
var value = new Window.frames[0]. Array;
Console.log (value instanceof array);//false
console.log (value.constructor = array);//false

However, the ToString () method can be invoked across prototype chains in different frameworks

var iframe = document.createelement (' iframe ');
Document.body.appendChild (IFRAME);
var value = new Window.frames[0]. Array;
Console.log (Object.prototype.toString.call (value));//[object Array]

ES5 has added the Array.isarray () method to ultimately determine whether a value is an array, regardless of the global context in which it was created

Array.isarray ()

var value = [123];
Console.log (Array.isarray (value));//true
var iframe = document.createelement (' iframe ');
Document.body.appendChild (IFRAME);
var value = new Window.frames[0]. Array;
Console.log (Array.isarray (value));//true

Stacks and queues
push ()

You can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array

Pop ()

Removes the last item from the end of the array, reduces the length of the array, and then returns the removed item

Shift ()

Moves the first item in the divisor group and returns the item, while the length of the array is reduced by 1 (combined with shift () and push () to simulate the queue)

Unshift ()

Add any items to the front of the array and return the new array length (combined with unshift () and pop () to simulate the queue in the opposite direction)

Attention The Ie7-browser unshift () method always returns undefined

var colors = [];
var count = Colors.push (' Red ', ' green ');
Console.log (colors,count);//[' red ', ' green '] 2
var count = Colors.pop ();
Console.log (colors,count);//[' red '] ' green '
var count = colors.unshift (' White ', ' black ');
Console.log (Colors,count);//["White", "Black", "Red"] 3
var count = Colors.shift ();
Console.log (Colors,count);//["Black", "red"] "white"

Sorting method
Reverse ()

Reverses the order of the arrays, returning the sorted array, and the original array order is changed

var array = [1,2,4,3,5];
Console.log (Array,array.reverse ());//[5,3,4,2,1] [5,3,4,2,1]
var array = [' str ', true,3];
Console.log (Array,array.reverse ());//[3,true, ' str '] [3,true, ' str ']

Sort ()

By default, array items are sorted in ascending order by string, and the sort method calls the ToString () method of each array item, then compares the resulting string sort, returns the sorted array, and the original array order changes

var array = [1,2,4,3,5];
Console.log (Array,array.sort ());//[1,2,3,4,5] [1,2,3,4,5]
var array = [' 3str ', 3,2, ' 2 '];
Console.log (Array,array.sort ());//[2, "2", 3, "3str"] [2, "2", 3, "3str"]
var array = [1,5,10,50];
Console.log (Array,array.sort ());//[1, 10, 5, 50] [1, 10, 5, 50]

[Note the]sort () method can accept a comparison function as an argument to specify which value precedes which value. The comparison function receives two arguments, returns a negative number if the first argument should precede the second argument, and returns 0 if the two arguments are equal, and returns a positive number if the first argument should be at the second argument

[Tips] Comparison function

 function Compare (value1,value2) {
  if (value1 < value2) {
    return-1;
  } else if (value1 > value2) {return
    1;
  } else{return
    0;
  }
var array = [' 5px ', 50,1,10];
When the number is compared to a string, the string ' 5px ' is converted to Nan, so that the result is False
Console.log (Array.Sort (Compare));//["5px", 1, 10, 50]

 

For numeric types or valueof () methods, the object type of the numeric type is returned, and the comparison function can be simplified to:

function Compare (value1,value2) {return
  value1-value2;
}
var array = [' 5px ', 50,1,10];
Console.log (Array.Sort (Compare));//["5px", 1,10,50]
var array = [5,50,1,10];
Console.log (Array.Sort (Compare));//[1,5,10,50]

[Tips] Create a random array

function Compare () {return
  math.random ()-0.5;
}
var array = [1,2,3,4,5];
Console.log (Array.Sort (Compare));//[2,1,5,4,3]

Operation method
Concat ()

Creates a new array based on all the items in the current array, creates a copy of the current array, then adds the received parameter to the end of the replica, and finally returns the newly constructed array (concat () without affecting the original array)

If you do not pass arguments to the concat () method, it simply copies the current array, or if the argument is one or more arrays, the method adds each item in those arrays to the result array, and if the passed value is not an array, the values are simply added to the end of the result array

var numbers = [1,2];
Console.log (Numbers,numbers.concat ()),//[1,2] [1,2]
Console.log (Numbers,numbers.concat ([5,4,3],[3,4,5],1,2) );//[1,2] [1,2,5,4,3,3,4,5,1,2]

Slice ()

Creates a new array based on one or more items in the current array, accepting one or two arguments, that is, to return the starting and ending positions of the items, and finally to return the new Array (slice () without affecting the original array)

If there are no arguments, the original array is returned; if there is only one argument, the slice () method returns all the items starting at the specified position from the argument to the end of the current array, and when there are two parameters, the method returns the item between the start and end positions, but not the ending position, if the argument is negative The array length is added as an argument, and an empty array is returned if the end position is less than the start position.

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));//[]

Splice ()

The original array changes to the modified array, and splice () returns an array of items that are deleted from the original array, or an empty array if no deletion is made. If the first argument is negative, the length of the array is added as an argument, and 0 is used as the argument if the second argument is negative.

[1] Delete: Two parameters are the position of the first item to be deleted, the number of items to delete

[2] Insert: Three parameters are starting position, 0 (cardinality to delete), items to insert

[3] Replace: Three parameters are starting position, number of items to delete, items to insert

 var numbers = [1,2,3,4,5];
Console.log (Numbers.splice (), 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]

Location method
ES5 added two location methods indexof (), LastIndexOf () for an array instance. Both methods receive two parameters: the item to find, an index that represents the position at which to find the start point (optional). Returns the position of the first lookup item that satisfies the condition in the array, or 1 if not found (the location method does not affect the original array)

[note] When comparing parameters, the method uses the strict equality operator

IndexOf () Look Back in front
LastIndexOf () looking forward from behind

var numbers = [1,2,3,4,5,4,3,2,1];
Console.log (Numbers.indexof (4));//3
Console.log (Numbers.lastindexof (4));//5
Console.log ( Numbers.indexof (4,4));//5
Console.log (Numbers.lastindexof (4,4));//3

 

var person = {name: ' Nicholas '};
var people = [{name: ' Nicholas '}];
var morepeople = [person];
alert (people.indexof);//-1, because person and people[0], although the values are the same, are two reference
alert (morepeople.indexof); 0 because person and morepeople[0] are the same reference
alert (Morepeople.indexof ({name: ' Nicholas '}));//-1 because it is not the same reference

[Tips] Returns all index values for an item that satisfies a condition

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]

The above is the detailed content of this article, I hope that the learning of JavaScript programming help.

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.