How to operate arrays with js and jquery
This time I will bring you the methods of js and jquery to operate arrays. What are the precautions for js and jquery to operate arrays? The following is a practical case, let's take a look.
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 objects (arrays is also an object), so 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);
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, 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 assigned directly when instantiated , 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. At this time, if alert(a==b) is used, 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 you use 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, for example
var a = new Array(); a[0] = new Array(); a[0][0] = 1; alert(a[0][0]); //弹出 1
var a = new Array([1,2,3], [4,5,6], [7,8,9]); var b = [[1,2,3], [4,5,6], [7,8,9]];
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); //弹出cat
As mentioned above, you can use the array [below] subscript] to read and write elements
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. For examplevar a = {x:"cat", y:"sunny"}; alert(a["y"]); //弹出sunny
2.1 Array Loop
var b = new Array(); b[2.2] = "XXXXX"; alert(b[2.2]); //-> XXXXX
var a = [1,2,3,4,5,6]; for(var i =0; i<a.length; i++){ alert(a[i]); }
var a = [1,2,3,4,5,6]; for(var e in a){ alert(e); }
2.2 Array
Commonly used functionsAppends an array after the existing array and returns the new array without affecting the current array. There is an array
var a = {x:1,y:2,z:3}; for(var e in a){ alert(e + ":" + a[e]); }
String connection
When using an array, 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 , remain as is after joining用指定间隔符连起来,把数组转为字符串
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
这个很容易理解,但需要注意的是只转换一维数组里面,如果数组里面还有数组,将不是采用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
数组里面的数组,并没用 * 连接
pop
删除数组最后一个元素,并返回该元素
var a = ["aa","bb","cc"]; document.write(a.pop()); // -> cc document.write(a); // -> aa, bb
如果数组为空,则返回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
跟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
结果是不是很意外,没错,排序并不是按整型大小,而是字符串对比,就是取第一个字符的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的特殊用法,不常用
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to operate arrays with js and jquery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to
