Home > Web Front-end > JS Tutorial > body text

Defining arrays and operations and jquery array operations in JavaScript jQuery_jquery

WBOY
Release: 2016-05-16 15:24:50
Original
1208 people have browsed it

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. Get to know 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 multi-dimensional arrays, but because arrays can contain objects (an array is also an object), arrays can achieve functions similar to multi-dimensional arrays by nesting each other

1.1 Define array

Declare an array with 10 elements

Copy code The code is as follows:

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 values

Copy code The code is as follows:

var a = new Array();
a[0] = 10;
a[1] = "aaa";
a[2] = 12.6;

As mentioned above, objects can be placed in arrays, such as 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();
Copy after login

Arrays can be assigned values ​​directly when instantiated, such as

var a = new Array(1, 2, 3, 4, 5);
var b = [1, 2, 3, 4, 5];
Copy after login

a and b are both arrays, but b uses an implicit declaration to create another instance. At this time, if alert(a==b) is used, false

will pop up

1.2 Multidimensional Array

Actually, Javascript does not support multi-dimensional arrays. In asp, you can use dim a(10,3) to define multi-dimensional arrays. In Javascript, if you use var a = new Array(10,3), an error will be reported
But 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
Copy after login

Assign value 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]];
Copy after login

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 ​​and calls are obtained through object name.properties and object.methods (), while arrays are obtained through subscripts. Values, Array Literals are very similar to arrays. 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);  //弹出cat
Copy after login

Create a simple object. Generally, the call is through aa.x. If it is used as Array literals, using alert(aa["x"]) will also pop up cat

var a = {x:"cat",  y:"sunny"};
alert(a["y"]); //弹出sunny
Copy after login

This is another way to create an object, the result is the same

2. Operation of array elements

As mentioned above, you can read and write elements through array[subscript]

The range of subscript is 0 – (23(superscript 2) -1). When the subscript is a negative number, floating point or even Boolean value, the array will be automatically converted to an object type, such as

var b  = new Array();
b[2.2]  = "XXXXX";
alert(b[2.2]); //-> XXXXX
Copy after login

This is equivalent to b["2.2"] = "XXXXX"

2.1 Array loop

var a = [1,2,3,4,5,6];
for(var i =0; i<a.length; i++){
alert(a[i]);
}
Copy after login

This is the most commonly used. Iterating through the array, the code will pop up 1 to 6 in sequence

There is another commonly used one

var a = [1,2,3,4,5,6];
for(var e in a){
alert(e);
}
Copy after login

Still pops up 1 to 6 in sequence. for...in is a traversal object (array is a special object) object. It is used on an array. Because the array has no attribute name, the value is output directly. This structural statement is used on the object. For example below

var a = {x:1,y:2,z:3};
for(var e in a){
alert(e  + ":" + a[e]);
}
Copy after login

At this time, e gets the attribute name, that is, x, y, x. To get the value, the array name [attribute] is used, so a[e] is equivalent to a["x"], a[" y”], a[“z”]

2.2 Common array functions

concat

Append an array after the existing array and return the new array without affecting the existing array

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 # 33
Copy after login

It should be noted that it can only be used for arrays or strings. If the connection (the previous a) is a numerical value, Boolean value, or object, an error will be reported. When a string is connected to an array, the string will be followed by the first element of the array. Splicing into new elements, while the array connection string will append new elements (I don’t know the reason for this, please disclose if you know). For arrays containing arrays and objects, they will remain intact after connection

join

Concatenate the arrays with specified separators and convert the arrays into strings

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
Copy after login

这个很容易理解,但需要注意的是只转换一维数组里面,如果数组里面还有数组,将不是采用join指定的字符串接,而是采用默认的toString(),例如

var a =  ['a','b','c','d','e','f','g',[11,22,33]];
alert(a.join(" * ")); // -> a * b * c * d * e * f * g *  11,22,33
Copy after login

数组里面的数组,并没用 * 连接

pop

删除数组最后一个元素,并返回该元素

var a =  ["aa","bb","cc"];
document.write(a.pop());  // -> cc
document.write(a);    // -> aa, bb
Copy after login

如果数组为空,则返回undefined

push

往数组后面添加数组,并返回数组新长度

var a =  ["aa","bb","cc"];
document.write(a.push("dd"));  // -> 4
document.write(a);    // -> aa,bb,cc,dd
document.write(a.push([1,2,3])); // -> 5
document.write(a);    // -> aa,bb,cc,dd,1,2,3
Copy after login

跟concat的区别在于,concat不影响原数组,直接返回新数组,而push则直接修改原数组,返回的是数组新长度

sort

数组排序,先看个例子

var a = [11,2,3,33445,5654,654,"asd","b"];
alert(a.sort()); // -> 11,2,3,33445,5654,654,asd,b
Copy after login

结果是不是很意外,没错,排序并不是按整型大小,而是字符串对比,就是取第一个字符的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
Copy after login

sort()方法有个可选参数,就是代码里的function,这是个简单的例子,不可对非数字进行排序,非数字需要多做判断,这里就不多讲

reverse

对数组进行反排序跟,sort()一样,取第一字符ASCII值进行比较

var a = [11,3,5,66,4];
alert(a.reverse()); // -> 4,66,5,3,11
Copy after login

如果数组里面还包含数组,则当为对象处理,并不会把元素解出来

>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
Copy after login

按理应该是11排最后面,因为这里把 4,11,33 当做完整的对象比较,所以被排在第一位。看不明白的话,用join()串起来,就明了多

shift

删除数组第一个元素,并返回该元素,跟pop差不多

var a =  ["aa","bb","cc"];
document.write(a.shift());  // -> aa
document.write(a);    // -> bb,cc
Copy after login

当数组为空时,返回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
Copy after login

注意该方法,在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));  // -> 空
Copy after login

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
Copy after login

注意该方法在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); }
Copy after login

布尔值则返回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
}
Copy after login

输出结果

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日
Copy after login

区别在于,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
Copy after login

数组也是对象,所以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
Copy after login

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]]]]); 创建一个数组并赋值
Copy after login

要说明的是,虽然第二种方法创建数组指定了长度,但实际上所有情况下数组都是变长的,也就是说即使指定了长度为5,仍然可以将元素存储在规定长度以外的,注意:这时长度会随之改变。

2、数组的元素的访问

var testGetArrValue=arrayObj[1]; //获取数组的元素值
arrayObj[1]= "这是新值"; //给数组元素赋予新的值
Copy after login

3、数组元素的添加

arrayObj. push([item1 [item2 [. . . [itemN ]]]]);// 将一个或多个新元素添加到数组结尾,并返回数组新长度
arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]);// 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度
arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]);//将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回""
Copy after login

4、数组元素的删除

arrayObj.pop(); //移除最后一个元素并返回该元素值
arrayObj.shift(); //移除最前一个元素并返回该元素值,数组中元素自动前移
arrayObj.splice(deletePos,deleteCount); //删除从指定位置deletePos开始的指定数量deleteCount的元素,数组形式返回所移除的元素
Copy after login

5、数组的截取和合并

arrayObj.slice(start, [end]); //以数组的形式返回数组的一部分,注意不包括 end 对应的元素,如果省略 end 将复制 start 之后的所有元素
arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); //将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组
Copy after login

6、数组的拷贝

arrayObj.slice(0); //返回数组的拷贝数组,注意是一个新的数组,不是指向
arrayObj.concat(); //返回数组的拷贝数组,注意是一个新的数组,不是指向
Copy after login

7、数组元素的排序
arrayObj.reverse(); //反转元素(最前的排到最后、最后的排到最前),返回数组地址
arrayObj.sort(); //对数组元素排序,返回数组地址

8、数组元素的字符串化

arrayObj.join(separator); //返回字符串,这个字符串将数组的每一个元素值连接在一起,中间用 separator 隔开。
toLocaleString 、toString 、valueOf:可以看作是join的特殊用法,不常用
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template