Js object-oriented learning Note 3 (Array object), Learning note array
1. array initialization:
// Three initialization Methods: new Array (); new Array (size); new Array (element0, element1,..., elementn );
2. Attributes
Constructor returns a reference to the array function that creates this object. Length setting or return the number of elements in the array. Prototype enables you to add attributes and methods to an object.
3. Method
Concat () connects two or more arrays and returns results.
Usage:
arrayObj.concat(aobj1,aobj2...);
Join () puts all elements of the array into a string. The elements are separated by the specified delimiter.
ToString () converts an array to a string and returns the result.
ValueOf () returns the original value of the array object
Usage:
Arr. join (".") arr. toString () // separated by commas (,) by default.
Pop () deletes and returns the last element of the array.
Push () adds one or more elements to the end of the array and returns a new length.
Usage:
arrObj.pop(); arrObj.push("theme");
Shift () deletes and returns the first element of the array.
Unshift () adds one or more elements to the beginning of the array and returns a new length.
Usage:
arrObj.shift() arrObj.unshift("element1")
The order of elements in the array is reversed by reverse.
Usage:
arrObj.reverse()
ToSource () returns the source code of the object.
arrObj.toSource(); // ["George", "John", "Thomas"]
Sort () sorts array elements
Usage:
Var arrA = [6, 2, 4, 3, 5, 1]; function desc (x, y) {if (x> y) return-1; if (x <y) return 1 ;} function asc (x, y) {if (x> y) return 1; if (x <y) return-1;} alert (arrA. sort (asc) // sort alert (arrA. sort (desc) // sort in descending order
Slice () returns the selected element from an existing array
Usage:
ArrA. slice () // returns the elements with an index of 2 to 4 [2, 4). The elements are pre-closed and then open. //
Splice () deletes an element and adds a new element to the array. Return the deleted Project
Usage:
arrayObject.splice(index,howmany,item1,.....,itemX)
Index is required. Integer that specifies the position of the added/deleted project. A negative number can be specified from the end of the array.
Howmany is required. The number of projects to delete. If it is set to 0, the project will not be deleted.
Item1,..., itemX (optional. Add a new project to the array.