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

Defining arrays and operations and jquery array operations in JavaScript jQuery

高洛峰
Release: 2017-02-06 09:55:05
Original
1253 people have browsed it

First of all, I will introduce you to the relevant knowledge of defining arrays and operations in javascript jquery. The specific content is as follows:

1. Understanding arrays

An array is a collection of certain types of data, and the data type It can be an integer, a string, or even an object
Javascript does not support multi-dimensional arrays, but because an array 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 the array

Declare an array with 10 elements

var a = new Array(10);
Copy after login

At this time, the memory space has been opened for a, containing 10 elements, use the array name plus [subscript] to Calling, such as a[2] but the element has not been initialized at this time, the call will return undefined

The following code defines a variable array and assigns it

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

As mentioned above, the array Objects can be placed inside, for example 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

The array can be assigned directly when instantiated, for example

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 Multi-dimensional array

In fact, Javascript does not support it For 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, in arrays you can Contains objects, so you can declare an element in the array as an array. For example,

var a = new Array();
a[0] = new Array();
a[0][0] = 1;
alert(a[0][0]); //弹出 1
Copy after login

has the same effect when assigning a 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

, a uses conventional 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, literal 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.property, object.method(), and arrays are obtained through the following Markers are used to get 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 objects, 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 the subscript is 0 – (23(superscript 2) -1). When the subscript is a negative number, floating point or even a 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 , traverse 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 e in a){
alert(e);
}
Copy after login

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, such as the following

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

At this time What e gets is 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 what is connected (the previous a) is a numerical value, Boolean value, or object, an error will be reported. When strings are connected to arrays, characters 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 if you know). For arrays containing arrays and objects, they will remain intact after connection

join

Connect the arrays with specified separators and convert them into strings

var a = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;];
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

This is easy to understand, but it should be noted that only conversion In a one-dimensional array, if there is an array in the array, the string connection specified by join will not be used, but the default toString() will be used, such as the array in the

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

array, It’s useless* connection

pop

Delete the last element of the array and return the element

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

If the array is empty, return undefined

push

Add an array after the array and return the new length of the array

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

The difference with concat is that concat does not affect the original array and returns it directly New array, while push directly modifies the original array, returning the new length of the array

sort

Array sorting, let’s look at an example first

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

Isn’t the result surprising? Yes, the sorting is not based on integer size, but on string comparison. That is to compare the ANSI code of the first character. The smaller one is ranked first. If they are the same, the second character is compared. If To compare by integer values, you can do this

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

The sort() method has an optional parameter, which is the function in the code. This is a simple example. Non-numbers cannot be sorted. , non-digits require more judgment, so I won’t go into details here

reverse

Reverse sorting of the array is the same as sort(), take the ASCII value of the first character for comparison

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

If the array also contains an array, it will be treated as an object and the elements will not be extracted.

>var a = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,[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 = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;];
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

更多JavaScript jQuery 中定义数组与操作及jquery数组操作相关文章请关注PHP中文网!


Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!