turn javascript array operations

2010-11-10  来源:本站原创  分类:Web  人气:108 

1, the creation of an array

The following is the contents of references:
vararrayObj = newArray (); / / Create an array
vararrayObj = newArray ([size]); / / create an array and specify the length of the note is not a ceiling, is the length of the
vararrayObj = newArray ([element0 [, element1 [,...[, elementN ]]]]); create an array and assign

To show that, although the second method creates an array of specified length, but in fact all cases are variable-length arrays, which means that even if the specified length of 5, you can still store the elements other than the prescribed length, Note: The length of time will change.
2, the elements of the array access
vartestGetArrValue = arrayObj [1]; / / Get the array element values
arrayObj [1] = "This is the new value"; / / array of elements to give new values
3, the addition of array elements
arrayObj.push ([item1 [item2 [...[ itemN ]]]]);// one or more new elements will be added to the end of the array, and returns the new length of the array
arrayObj.unshift ([item1 [item2 [...[ itemN ]]]]);// one or more new elements will be added to the array of start elements in the array automatically retracting the length of the returned array of new
arrayObj.splice (insertPos, 0, [item1 [, item2 [,...[, itemN ]]]]);// one or more new elements into the array specified location, the location of the element automatically inserted after the shift return "."
4, delete the array elements
arrayObj.pop ();// remove last element and returns the element value
arrayObj.shift ();// remove the front element and returns the element value, the array elements automatically forward
arrayObj.splice (deletePos, deleteCount); / / delete starting from the specified location deletePos deleteCount specified number of elements, the array element returned are removed
5, the interception and the combined array
arrayObj.slice (start, [end ]);// an array returns an array of part of the end note does not include the corresponding element, if you omit the end to copy all the elements after the start
arrayObj.concat ([item1 [, item2 [,...[, itemN ]]]]);// multiple arrays (also can be a string, or a mix of arrays and strings) to connect to an array, Returns a new array of the connected
6, a copy of the array
arrayObj.slice (0); / / returns a copy of the array array, attention is a new array, not the point
arrayObj.concat ();// returns a copy of an array of arrays, attention is a new array, not the point
7, the array elements to sort
arrayObj.reverse ();// reversal element (the most pre-routed to the end, the final routed to the front), the return address of the array
arrayObj.sort ();// sort of array elements, the return address of the array
8, a string of array elements
arrayObj.join (separator); / / return string, the string value of each element of the array together, separated by a separator separated.
toLocaleString, toString, valueOf: join can be seen as a special use, not used two of the three properties of the array object
1, length attribute
Length property indicates the length of the array, that is where the number of elements. Because the array index is always starting from 0, so an array of upper and lower limits are: 0 and length-1. And the difference is that most other languages, JavaScript array length property is variable and that this requires special attention. When the length property is set to be greater, the entire array will not change the status of a matter of fact, just the length attribute larger; when the length property is set than the original hours, the original index of the array elements is greater than or equal to the length values have all been lost. Here is an example demonstrates changing the length property:
vararr = [12,23,5,3,25,98,76,54,56,76];
/ / Defines a number of the array contains 10
alert (arr.length); / / display the array of length 10
arr.length = 12; / / increase the length of the array
alert (arr.length); / / display the length of the array 12 has been changed
alert (arr [8 ]);// shows the value of element 9, 56
arr.length = 5; / / the length of the array down to 5, the index is equal to or more than 5 elements are discarded
alert (arr [8 ]);// display element 9 has become "undefined"
arr.length = 10; / / array length will return to 10
alert (arr [8 ]);// Although the length was restored to 10, but the first nine elements can not recover, showing "undefined"
Code from the above we can clearly see the nature of the length property. But the length objects can not only set explicitly, it may be implicitly modified. JavaScript can be used in a non-declared variables, the same can also use an undefined array element (referring to an index greater than or equal to the length of the element), then, length property value will be set to the value of the index used by the elements plus 1. For example, the following code:
vararr = [12,23,5,3,25,98,76,54,56,76];
alert (arr.length);
arr [15] = 34;
alert (arr.length);
The same code is to define a containing an array of 10 numbers, can be seen through the alert statement, its length is 10. Then use the index for the 15 elements, to a value of 15, that arr [15] = 34, then alert statement when the length of the output array is to be a 16. However, for strongly typed programming used to developers, this is a very surprising feature. In fact, the use of newArray () in the form to create the array, the initial length is 0, which is undefined elements of the operation, only to change the length of the array.
Can be seen from the above description, length property is so amazing, you can easily use it to increase or decrease the capacity of the array. Therefore, understanding of the length property will help in the development process flexibility.
2, prototype property returns a reference to the prototype object type. prototype property is shared object.
objectName.prototype
objectName parameter is the object name of the object.
Description: The object of the class prototype property provides a set of basic functions. A new instance of the object "inheritance" given to the operation of the prototype of the object.
For the array object to the following examples illustrate the use of prototype properties.
Added to the array object returns the largest element in the array values. To do this, declare a function to add it Array.prototype, and use it.

The following is the contents of references:
functionarray_max ()
{
vari, max = this [0];
for (i = 1; i <this.length; i + +)
{
if (max <this [i])
max = this [i];
}
returnmax;
}
Array.prototype.max = array_max;
varx = newArray (1,2,3,4,5,6);
vary = x.max ();

The code is executed, y the maximum value stored in the array x, or 6.
3, constructor property that created the object function.
object.constructor / / object is the object or function name.
Description: constructor property is a prototype of the object of all members. They include Global and Math in addition to all JScript objects other than natural objects. constructor property contains a specific object instance on the structure function of the reference.
For example:
x = newString ("Hi");
if (x.constructor == String) / / for processing (condition is true.)
Or
functionMyFunc {
/ / Function body.
}
y = newMyFunc;
if (y.constructor == MyFunc) / / for processing (condition is true.)
The array is:
y = newArray ();

Array of methods to determine whether
vararrayVar = [\ "aaa \", \ "bbb \", \ "ccc \"];
varnonArrayVar = {length: 4, otherAttribute: \ "attr \"};
document.write (arrayVar.constructor == Array);
document.write (\ "<br/> \");
document.write (nonArrayVar.constructor == Array); result is true, false

Conversion can be used on the array []. Slice.call () or Array.prototype.slice.call (), but the IE6, IE7 DOM under the element set error when using this operation, other browsers (Firefox, Opera, Safari ) are normal sample code:
(Function () {
/ / SupportedbyFirefox, IE6, IE7, Opera, Safari
varargArray = []. slice.call (arguments); / / argumentsisnotanarray,
//[]. Slice.call () willmakeanewarraywitharguments
document.write (argArray.reverse (). join (\ "& \ "));// result: www & 2 & 1
document.write (\ "<br/> \"); [Page]

/ / SupportedbyFirefox, IE6, IE7, Opera, Safari
vararrayLike = {0: \ "ccc \", 1:1,2: \ "eee \", 3:8, length: 4}; / / anobjectthatlookslikeanobject
vartrueArray = []. slice.call (arrayLike, 2, arrayLike.length); / / makeanewarraywitharrayLike
trueArray.push (\ "2008-02-12 \");
document.write (trueArray.join (\ "| \ "));// result: eee | 8 | 2008-02-12
document.write (\ "<br/> \");

/ / SupportedbyFirefox, Opera, Safari
varobj = document.createElement (\ "ul \");
obj.innerHTML = '<li> AAAAAA </ li> <listyle=\"display:none;\"> BBBBBB </ li>

<li> CCCCCC </ li> <li> DDDDDD </ li> ';
varnodeList = obj.getElementsByTagName (\ "li \ ");// DOMElementcollections
document.write (nodeList.length + \ "linodefound! <br/> \");
varnodeArray = []. slice.call (nodeList); / / makeanewarraywithnodeList
for (vari = 0; i <nodeArray.length; i + +) {
document.write (nodeArray [i]. textContent | | nodeArray [i]. innerText);
document.write (\ "$ \");
} / / Result: AAAAAA $ BBBBBB $ CCCCCC $ DDDDDD $
}) (1,2, \ "www \");
grep, map
Perl language with out of something, jQuery which will use its own grep and map to achieve
grep
Grep operation on the array, means the code like this:
ArraynewArray = grep (condition, oldArray), this operation will oldArray traverse each element of the array, if the current processing element eligible condition, is added to the returned array
jQuery in grep like this: function (elems, callback), elems is a collection of DOM elements, callback number of selector expressions to achieve the function, if the callback returns true if the elements that meet the current selector expression processing

map

The difference is that with grep, map not be conditional, but the implementation of each element of the array specified operation is a cyclic process of modification [Page]

Like dynamic language style, and can add a grep and map array, for example:
Array.prototype.grep = function (condition, operation, inverse) {
if (arguments.length <1) return [];

vartester;
if (typeofcondition == \ "function \") tester = condition;
elseif (condition.constructor == RegExp) tester = function (e, i) {returncondition.test (e);};
elseif (typeofcondition == \ "string \")
try {
tester = eval (\ "false | | function (e, i) {return \" + condition + \ ";} \");
} Catch (e) {
}
elsetester = function (e, i) {returnfalse;};
if (! tester) return [];

varcommand;
if (typeofoperation == \ "function \") command = operation;
elseif (typeofoperation == \ "string \")
try {
command = eval (\ "false | | function (e, i) {\" + operation + \ "; returne;} \");
} Catch (e) {
}
if (typeofcommand! = \ "function \") command = function (e, i) {returne;};

varresult = [], match, t;
for (vari = 0; i <this.length; i + +) {
match = tester (this [i], i);
if (match) t = command (this [i], i);
if (match & &! inverse & & t! = null) t.constructor == Array? result.concat (t): result.push (t);
elseif (! match & & inverse) result.push (this [i]); [Page]
}

returnresult;
};
Array.prototype.map = function (callback) {
if (! callback | | typeofcallback! = \ "function \") returnthis;
for (vari = 0; i <this.length; i + +) callback (this [i], i);
returnthis;
}; Use the example:
varoldArray = [2,7,8,5,1,9,2,6,0];
varnewArray1 = oldArray.grep (\ "i% 2 == 0 \ ");// returnelementswithevenindex
varnewArray2 = oldArray.grep (\ "e% 2 == 1 \ ");// returnelementswithoddvalue
document.write (newArray1 + \ "<br/> \ ");// result: 2,8,1,2,0
document.write (newArray2 + \ "<br/> \ ");// result: 7,5,1,9

oldArray = [\ "aa \", \ "bbbb \", \ "abcdefg \", \ "ccccc \", \ "111121111 \", \ "999999999 \"];
varnewArray3 = oldArray.grep (/ (\ \ w) \ \ 1 {4 ,}/);
document.write (newArray3 + \ "<br/> \ ");// result: ccccc, 999999999 typical style of jQuery code:
varobj = document.createElement (\ "ul \");
obj.innerHTML = '<li> AAAAAA </ li> <listyle=\"display:none;\"> BBBBBB </ li>

<li> CCCCCC </ li> <li> DDDDDD </ li> ';
document.body.appendChild (obj);

window.setInterval (function () {
/ / MakeanewaarraywithDOMElementcollection
varliList = obj.getElementsByTagName (\ "li \");
varliArray = [];
for (vari = 0; i <liList.length; i + +) liArray.push (liList [i]);
/ / Grepforarraysexample
liArray
. Grep ('e.style [\ "display \"] == \ "none \"', 'e.style [\ "display \"] = \ "\";', true)

. Map (function (e, i) {e.style [\ "display \"] = \ "none \ ";});
}, 1500);

相关文章
  • turn javascript array operations 2010-11-10

    1, the creation of an array The following is the contents of references: vararrayObj = newArray (); / / Create an array vararrayObj = newArray ([size]); / / create an array and specify the length of the note is not a ceiling, is the length of the var

  • javascript array operations Daquan 2010-06-11

    shift: first delete the original array, and returns the value of the element removed; If the array is empty then return undefined var a = [1,2,3,4,5]; var b = a.shift (); / / a: [2,3,4,5] b: 1 unshift: the parameter to the beginning of the original a

  • Javascript array with the framework of the static class to basically achieve 2008-05-23

    Javascript array with the framework of the static class to basically achieve This article is I always want to write about. There is no technical content, but to share with you some of my in the development process a number of tips bar. First Laijiang

  • Javascript array and its operation 2010-06-01

    This article describes the contents of the following aspects: 1. How to create an array 2. How to array operations (add, delete, read) 3. Array of common methods and properties How to create an array, generally set according to a simple initializatio

  • JavaScript Array Remove 最好的删除数组元素的方法 2012-11-15

    JavaScript Array Remove 原文地址: http://ejohn.org/blog/javascript-array-remove/ I have another handy method, that I recently developed, that allows you to simply remove an item - or a group of items - from an array. Like with my implementation of JavaSc

  • JavaScript Array Object Reference Manual (directory) 2009-03-18

    JavaScript Array Object Reference Manual Note: FF = Firefox, N = Netscape, IE = Internet Explorer Array Object Ways Description FF N IE concat () Connect two or more of the array, and return results 1 4 4 join () Put all the elements of the array int

  • JavaScript Array Object Reference Manual prototype property 2009-03-19

    JavaScript prototype property Return JavaScript Array Object Reference Manual (directory) The definition and use of prototype property to the object (in this case refers to Array array) to add properties and methods. Grammar Array.prototype Followed.

  • JavaScript array length property returns the value of 2010-01-15

    Javascript array length property of the return value is the array defined in the highest elements plus a subscript after the derived value. <br> In this example, first declare a variable as an array, and then to a first element of assignment, that i

  • In the JavaScript array to find and replace elements in the array. 2009-01-21

    Source: http://blog.iyi.cn/hily/archives/2005/10/javascript_3.html JavaScript provides a substring in the string to find a function indexOf (), lastIndexOf (), search (), also provides a string replacement function replace (), but these functions do

  • JS ARRAY Array Operations 2009-11-12

    The recent use of the Array on them a finishing, the contents of the text to read the article excerpt others add their own operation by experiment, not entirely original. The three properties of the array object 1, length attribute length property Le

  • JavaScript Array Functions 2009-07-15

    A recent review JavaScript: Reproduced the article a welcome to exchange JavaScript! ! Javascript Array library shift: delete the original array the first item, and return to remove the element value; if the array is empty then return undefined var a

  • Chapter 5 Core Series JavaScript array 2010-04-24

    Chapter array JavaScript is a more interesting array of topics, while we have a array (Array), but according to an array of objects on the point of view, is more like a lot of things mixed in with the results. The traditional programming languages su

  • Some elements of JavaScript array interception 2010-12-01

    Some elements of JavaScript array interception slice () method for the Array object as a substring () method for a String object. This method is simply to tell what elements you want to intercept. This is very useful, for instance, use the URL when y

  • Summary of some of the common array operations 2011-09-09

    Summary of some of the common array operations Transfer http://www.nowamagic.net/datastructures/ds_SumaryOfArrayControl.php Array is the most basic data structure, a programmer on the operation of an array of the most frequently used. There will be s

  • javascript Array 数组常用方法 2013-10-15

    这篇文章主要介绍了javascript Array 数组常用方法 ,需要的朋友可以参考下 (1)基本的数组方法 1.join() Array.join()方法将数组中所有元素都转化为字符串并连接在一起,返回最后生成的字符串.可以自己指定分隔的符号,如果不指定,默认使用逗号 var arr = [1,2,3]; console.log(arr.join());//"1,2,3" console.log(arr.join("-"));//"1-2-3"

  • javascript Array.prototype.slice的使用示例 2014-01-20

    javascript Array.prototype.slice除了常见的从某个数组中抽取出新的数组外,它还有一些其他的用法,下面就为大家讲这些妙用 经常的,可以看到Array.prototype.slice(arguments, 0); 这个写法可以用于function() {} 内,这样可以将函数的参数列表转换成一个真正的数组.请看一个例子: var slice = Array.prototype.slice; var toString = Object.prototype.toString

  • javaScript array(数组)使用字符串作为数组下标的方法 2014-03-28

    这篇文章主要介绍了javaScript array(数组)使用字符串作为数组下标的方法,大家可以测试一下看看 Array是从Object那里继承下.它具备Object所有的功能和特性.下面是Object的情况: 新建: var object = new Object(); 增加: object[strIndex ] = value; (strIndex 为string) 删除: delete object[strIndex ]; 遍历: for ( var strObjIndex in obje

  • 浅谈JavaScript Array对象 2014-07-05

    这篇文章主要介绍了JavaScript Array对象的相关资料,需要的朋友可以参考下 Array 数组 1. 介绍 数组是值的有序集合.每个值叫做一个元素,而每个元素在数组中有一个位置,以数字表示,称为索引.JavaScript数组是无类型:数组元素可以是任意类型,并且同一个数组中的不同元素也可能有不同的类型. --<JavaScript权威指南(第六版)> 2. 定义 var names = new Array("张三", "李四", "王

  • javaScript Array(数组)相关方法简述 2014-09-04

    javaScript Array(数组)相关方法简述,让大家更快的熟悉array数组的用法. 1.创建Array对象(赋初值情况下)两种方法: var aColor=new Array('red','black','yellow'); alert(aColor.toString());//output: red,black,yellow var aColor=['red','black','blue']; alert(aColor.toString());//output: red,black,

  • javascript array 2013-07-18

    the delete operator on the array element as opposed to using theArray.splice method? delete 操作符 和 Array.splice 方法的不同 delete 不删除 element ,而是设置 该元素为 undefined splice从空间里删除元素 Best way to find an item in a JavaScript array? [duplicate] 在数组中查找元素的最好方法 func