Home >Web Front-end >JS Tutorial >How does jquery define and operate arrays and array elements?
First of all, I will introduce to you the relevant knowledge of defining arrays and operations in javascript jquery. The specific content is as follows:
1. Understand arrays
An array is a collection of certain types of data. The data type can be an integer, a string, or even an object.
Javascript does not support multidimensional arrays, but because the array can contain Object (an array is also an object), so arrays can achieve functions similar to multi-dimensional arrays by nesting each other
1.1 Define an array
Declare an array with 10 elements
var a = new Array(10);
At this time, the memory space has been opened for a, containing 10 elements. Use the array name plus [subscript] to call, such as a[2], but the element has not been initialized at this time, and the call will return undefined
The following code defines a variable array and assigns a value
var a = new Array(); a[0] = 10; a[1] = "aaa"; a[2] = 12.6;
As mentioned above, objects can be placed in the array. For example, in the following code
var a = new Array(); a[0] = true; a[1] = document.getElementByIdx_x("text"); a[2] = {x:11, y:22}; a[3] = new Array();
the array can be instantiated When assigning values directly, for example
var a = new Array(1, 2, 3, 4, 5); var b = [1, 2, 3, 4, 5];
a and b are both arrays, but b uses an implicit declaration to create another instance. If alert(a==b) is used at this time, false## will pop up.
#1.2 Multi-dimensional array
In fact, Javascript does not support multi-dimensional arrays. In asp, you can use dim a(10,3) to define multi-dimensional arrays. In Javascript, if Using var a = new Array(10,3) will report an errorBut as mentioned before, arrays can contain objects, so you can declare an element in the array as an array, such as
var a = new Array(); a[0] = new Array(); a[0][0] = 1; alert(a[0][0]); //弹出 1
Assignment when declaring
var a = new Array([1,2,3], [4,5,6], [7,8,9]); var b = [[1,2,3], [4,5,6], [7,8,9]];The effect is the same, a uses regular instantiation, b is an implicit declaration, and the result is a multi-dimensional array
1.3 Array literals
I really don’t know what this is called in Chinese, text array? Speaking of arrays, we have to talk about Array Literals. Arrays are actually special objects. Objects have unique
properties and methods . Values can be obtained and called through object name.property and object.method() , and arrays obtain values through subscripts. Array Literals are similar to arrays in that they are both collections of a certain data type. However, Array Literals is fundamentally an object, and its declaration and call are different from arrays
var aa = new Object(); aa.x = "cat"; aa.y = "sunny"; alert(aa.x); //弹出catCreate a simple object. Generally, the call is through aa. A
way to create an object
, the result is the same2. Operation of array elementsAs mentioned above , you can read and write elements through array [subscript]. The range of the subscript is 0 – (23 (superscript 2) -1). When the subscript is a negative number, a floating point or even a Boolean value, the array will Automatically converted to object type, for example
var a = {x:"cat", y:"sunny"}; alert(a["y"]); //弹出sunnyThis is equivalent to b["2.2"] = "XXXXX"
2.1 Loop of array
var b = new Array(); b[2.2] = "XXXXX"; alert(b[2.2]); //-> XXXXXThis is the most commonly used. When traversing the array, the code will pop up 1 to 6 in sequence.
There is also a commonly used
var a = [1,2,3,4,5,6]; for(var i =0; i<a.length; i++){ alert(a[i]); }which will pop up 1 to 6 in sequence. for...in is the traversal object. (Arrays are special objects) Objects are used on arrays. Because arrays have no attribute names, the values are output directly. This structural statement is used on objects. For example, below
var a = [1,2,3,4,5,6]; for(var e in a){ alert(e); }At this time, e gets the attributes. name, that is, x, y, x, and to get the value, use the array name [attribute], so a[e] is equivalent to a["x"], a["y"], a["z"]
2.2 Array
Commonly used functions Append an array after the existing array and return New array, does not affect existing arrayvar a = {x:1,y:2,z:3}; for(var e in a){ alert(e + ":" + a[e]); }It should be noted that it can only be used for arrays or strings. If the connected (a in front) is a numerical value, Boolean value, or object, an error will be reported,String connectionWhen arrays are connected, the string will be spliced with the first element of the array to form a new element, while the array connection string will append new elements (I don’t know the reason for this, please disclose it if you know it). For arrays If it contains arrays and objects, keep them as they are after connection Connect them with the specified separator and convert the array into a string
var a = [123]; var b = "sunnycat"; var c = ["www",21,"ido"]; var d = {x:3.14, y:"SK"}; var e = [1,2,3,4,[5,6,[7,8]]]; alert(a.concat(b)); // -> 123,sunnycat alert(a); // -> 123 alert(b.concat(c, d)); // -> sunnycatwww,21,ido[object Object] alert(c.concat(b)); // -> www,21,ido,sunnycat alert(e.concat(11,22,33).join(" # ")); // -> 1 # 2 # 3 # 4 # 5,6,7,8 # 11 # 22 # 33This is easy to understand, but it should be noted that only the one-dimensional array
is converted
. If there are arrays in the array, the string connection specified by join will not be used, but The default toString() is used, for example, the array in the var a = ['a','b','c','d','e','f','g'];
lert(a.join(",")); // -> a,b,c,d,e,f,g 相当于a.toString()
alert(a.join(" x ")); // -> a x b x c x d x e x f x g
array does not use * to connect
pop
var a = ['a','b','c','d','e','f','g',[11,22,33]]; alert(a.join(" * ")); // -> a * b * c * d * e * f * g * 11,22,33If the array is empty, return undefined
push
Add the array after the array , and returns the new length of the arrayvar a = ["aa","bb","cc"]; document.write(a.pop()); // -> cc document.write(a); // -> aa, bbThe difference with concat is that concat does not affect the original array and directly returns the new array, while push directly modifies the original array and returns the new length of the array
sort
数组排序,先看个例子
var a = [11,2,3,33445,5654,654,"asd","b"]; alert(a.sort()); // -> 11,2,3,33445,5654,654,asd,b
结果是不是很意外,没错,排序并不是按整型大小,而是字符串对比,就是取第一个字符的ANSI码对比,小的排前面,相同的话取第二个字符再比,如果要按整型数值比较,可以这样
var a = [11,2,3,33445,5654,654]; a.sort(function(a,b) { return a - b; }); alert(a); // -> 2,3,11,654,5654,33445
sort()方法有个可选参数,就是代码里的function,这是个简单的例子,不可对非数字进行排序,非数字需要多做判断,这里就不多讲
reverse
对数组进行反排序跟,sort()一样,取第一字符ASCII值进行比较
var a = [11,3,5,66,4]; alert(a.reverse()); // -> 4,66,5,3,11
如果数组里面还包含数组,则当为对象处理,并不会把元素解出来
>var a = ['a','b','c','d','e','f','g',[4,11,33]]; alert(a.reverse()); // -> 4,11,33,g,f,e,d,c,b,a alert(a.join(" * ")); // -> 4,11,33 * g * f * e * d * c * b * a
按理应该是11排最后面,因为这里把 4,11,33 当做完整的对象比较,所以被排在第一位。看不明白的话,用join()串起来,就明了多
shift
删除数组第一个元素,并返回该元素,跟pop差不多
var a = ["aa","bb","cc"]; document.write(a.shift()); // -> aa document.write(a); // -> bb,cc
当数组为空时,返回undefined
unshift
跟shift相反,往数组最前面添加元素,并返回数组新长度
var a = ["aa","bb","cc"]; document.write(a.unshift(11)); // -> 4 注:IE下返回undefined document.write(a); // -> 11,aa,bb,cc document.write(a.unshift([11,22])); // -> 5 document.write(a); // -> 11,22,11,aa,bb,cc document.write(a.unshift("cat")); // -> 6 document.write(a); // -> cat,11,22,11,aa,bb,cc
注意该方法,在IE下将返回undefined,貌似微软的bug,我在firefox下则能正确发挥数组新长度
slice
返回数组片段
var a = ['a','b','c','d','e','f','g']; alert(a.slice(1,2)); // -> b alert(a.slice(2)); // -> c,d,e,f,g alert(a.slice(-4)); // -> d,e,f,g alert(a.slice(-2,-6)); // -> 空
a.slice(1,2),从下标为1开始,到下标为2之间的数,注意并不包括下标为2的元素
如果只有一个参数,则默认到数组最后
-4是表示倒数第4个元素,所以返回倒数的四个元素
最后一行,从倒数第2开始,因为是往后截取,所以显然取不到前面的元素,所以返回空数组,如果改成 a.slice(-6,-2) 则返回b,c,d,e
splice
从数组删除某片段的元素,并返回删除的元素
var a = [1,2,3,4,5,6,7,8,9]; document.write(a.splice(3,2)); // -> 4,5 document.write(a); // -> 1,2,3,6,7,8,9 document.write(a.splice(4)); // -> 7,8,9 注:IE下返回空 document.write(a); // -> 1,2,3,6 document.write(a.splice(0,1)); // -> 1 document.write(a); // -> 2,3,6 document.write(a.splice(1,1,["aa","bb","cc"])); // -> 3 document.write(a); // -> 2,aa,bb,cc,6,7,8,9 document.write(a.splice(1,2,"ee").join("#")); // -> aa,bb,cc#6 document.write(a); // -> 2,ee,7,8,9 document.write(a.splice(1,2,"cc","aa","tt").join("#")); // -> ee#7 document.write(a); // -> 2,cc,aa,tt,8,9
注意该方法在IE下,第二个参数是必须的,不填则默认为0,例如a.splice(4),在IE下则返回空,效果等同于a.splice(4,0)
toString
把数组转为字符串,不只数组,所有对象均可使用该方法
var a = [5,6,7,8,9,["A","BB"],100]; document.write(a.toString()); // -> 5,6,7,8,9,A,BB,100 var b = new Date() document.write(b.toString()); // -> Sat Aug 8 17:08:32 UTC+0800 2009 var c = function(s){ alert(s); } document.write(c.toString()); // -> function(s){ alert(s); }
布尔值则返回true或false,对象则返回[object objectname]
相比join()方法,join()只对一维数组进行替换,而toString()则把整个数组(不管一维还是多维)完全平面化
同时该方法可用于10进制、2进制、8进制、16进制转换,例如
var a = [5,6,7,8,9,"A","BB",100]; for(var i=0; i<a.length; i++){ document.write(a[i].toString() + " 的二进制是 " + a[i].toString(2) + " ,八进制是 " + a[i].toString(8) + " ,十六进制是 " + a[i].toString(16)); // -> 4,5 }
输出结果
5 的二进制是 101 ,八进制是 5 ,十六进制是 5
6 的二进制是 110 ,八进制是 6 ,十六进制是 6
7 的二进制是 111 ,八进制是 7 ,十六进制是 7
8 的二进制是 1000 ,八进制是 10 ,十六进制是 8
9 的二进制是 1001 ,八进制是 11 ,十六进制是 9
A 的二进制是 A ,八进制是 A ,十六进制是 A
BB 的二进制是 BB ,八进制是 BB ,十六进制是 BB
100 的二进制是 1100100 ,八进制是 144 ,十六进制是 64
转换只能在元素进行,如果对整个数组进行转换,则原封不动返回该数组
toLocaleString
返回本地格式字符串,主要用在Date对象上
var a = new Date(); document.write(a.toString()); // -> Sat Aug 8 17:28:36 UTC+0800 2009 document.write(a.toLocaleString()); // -> 2009年8月8日 17:28:36 document.write(a.toLocaleDateString()); // -> 2009年8月8日
区别在于,toString()返回标准格式,toLocaleString()返回本地格式完整日期(在【控制面板】>>【区域和语言选项】,通过修改[时间]和[长日期]格式),toLocaleDateString()跟toLocaleString()一样,只是少了时间
valueOf
根据不同对象返回不同原始值,用于输出的话跟toString()差不多,但是toString()是返回string类型,而valueOf()是返回原对象类型
var a = [1,2,3,[4,5,6,[7,8,9]]]; var b = new Date(); var c = true; var d = function(){ alert("sunnycat"); }; document.write(a.valueOf()); // -> 1,2,3,4,5,6,7,8,9 document.write(typeof (a.valueOf())); // -> object document.write(b.valueOf()); // -> 1249874470052 document.write(typeof(b.valueOf())); // -> number document.write(c.valueOf()); // -> true document.write(typeof(c.valueOf())); // -> boolean document.write(d.valueOf()); // -> function () { alert("sunnycat"); } document.write(typeof(d.valueOf())); // -> function
数组也是对象,所以typeof (a.valueOf())返回object,返回的依然是个多维数组
var a = [1,2,3,[4,5,6,[7,8,9]]]; var aa = a.valueOf(); document.write(aa[3][3][1]); // -> 8
Date对象返回的是距离1970年1月1日的毫秒数,
Math和Error对象没有valueOf方法
Jquery 数组操作
在jquery中处理JSON数组的情况中遍历用到的比较多,但是用添加移除这些好像不是太多。
今天试过json[i].remove(),json.remove(i)之后都不行,看网页的DOM对象中好像JSON数据是以数组的形式出现的,查阅了下相关JS中数组的操作一试果然很爽。
记录下来。
1、数组的创建
var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限,是长度 var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); 创建一个数组并赋值
要说明的是,虽然第二种方法创建数组指定了长度,但实际上所有情况下数组都是变长的,也就是说即使指定了长度为5,仍然可以将元素存储在规定长度以外的,注意:这时长度会随之改变。
2、数组的元素的访问
var testGetArrValue=arrayObj[1]; //获取数组的元素值 arrayObj[1]= "这是新值"; //给数组元素赋予新的值
3、数组元素的添加
arrayObj. push([item1 [item2 [. . . [itemN ]]]]);// 将一个或多个新元素添加到数组结尾,并返回数组新长度 arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]);// 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度 arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]);//将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回""
4、数组元素的删除
arrayObj.pop(); //移除最后一个元素并返回该元素值 arrayObj.shift(); //移除最前一个元素并返回该元素值,数组中元素自动前移 arrayObj.splice(deletePos,deleteCount); //删除从指定位置deletePos开始的指定数量deleteCount的元素,数组形式返回所移除的元素
5、数组的截取和合并
arrayObj.slice(start, [end]); //以数组的形式返回数组的一部分,注意不包括 end 对应的元素,如果省略 end 将复制 start 之后的所有元素 arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); //将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组
6、数组的拷贝
arrayObj.slice(0); //返回数组的拷贝数组,注意是一个新的数组,不是指向 arrayObj.concat(); //返回数组的拷贝数组,注意是一个新的数组,不是指向
7、数组元素的排序
arrayObj.reverse(); //反转元素(最前的排到最后、最后的排到最前),返回数组地址
arrayObj.sort(); //对数组元素排序,返回数组地址
8、数组元素的字符串化
arrayObj.join(separator); //返回字符串,这个字符串将数组的每一个元素值连接在一起,中间用 separator 隔开。 toLocaleString 、toString 、valueOf:可以看作是join的特殊用法,不常用
jQuery操作对象数组元素的3种方法以及一种错误方法介绍
<div id="div1"> <span>a</span> <span>b</span> <span>c</span> </div>
1.错误方式:不能用[]方式取jquery对象数组,如下:
$(function() { var div_span = $("#div1 span"); for( var i = 0; i < div_span.length; i++ ) { div_span.[i].html(i); } });
这样无效.
2.可以用jquery的eq()方法来选择:
for( var i = 0; i < div_span.length; i++ ) { div_span.eq(i).html(i); }
3.可以用each()方法来遍历:
$(function() { var div_span = $("#div1 span"); var i = 0; div_span.each( function(){ $(this).html(i); i++; }); });
each()遍历的时候,如果用$(this)得到的是jquery对象,如果直接用this,得到的是DOM对象
4.纯js代码获取的DOM对象数组,可以用[]的方式获取数组元素
后面3种是正确的方法,第一种是错误的,把他放在第一个,是因为要强调下,以后不能再犯同样的错误了,小伙伴们可要看仔细哈。
The above is the detailed content of How does jquery define and operate arrays and array elements?. For more information, please follow other related articles on the PHP Chinese website!