发布时间:2022-08-09 文章分类:编程知识 投稿人:李佳 字号: 默认 | | 超大 打印

Creating Arrays in jQuery

At the very basic level you can create an empty array like this

view plain

print?

1 var myArray = [] ;

I like to use empty arrays because I will fill them programmatically with HTML that is available on the page. Let’s say you have created a list from a database that looks like this

view plain

print?

1 <ul id="userList">
2 <li id="user1">Jim</li>
3 <li id="user2">Mike</li>
4 <li id="user3">Jake</li>
5 </ul>

Filling an Empty Array with data from an Unordered List

Using the list above we can put the users ID and Names into the array for use later

view plain

print?

01 // we are using the array created above
02 var userList = $('#userList');
03 userList.children('li').each(function() {
04 var userID = $(this).attr('id');
05 var userName = $(this).text();
06 myArray.push({
07 'id':userID,
08 'name':userName
09 });
10 });

Display Data in a jQuery Array

Once the data is in the array you will want to make sure it looks good. Here’s how you can show the data in the array quickly.

view plain

print?

1 var result = $('body');
2 $.each(myArray, function(i, v) {
3 result.append($('<p>').hide().text('Name: ' + v.name + ' with ID: ' + v.id).show('slow'));
4 });

I am basically creating a P tag for each item in the array and creating text in each paragraph with the information from the array. Using $.each() and .append() functions.

Comparing and Removing from Arrays in jQuery

Let’s say you don’t want to have Jim in the array anymore, we can use the same $.each() along with the .splice() function to accomplish this.

view plain

print?

1 var removeMe;
2 $.each( myArray, function(i, v) {
3 if( v.name == 'Jim' ) {
4 removeMe = i;
5 }
6 });
7 myArray.splice(removeMe,1);

This is only removing one item, but let’s say you want to compare two arrays and remove all the items in one array from the items in the other array?We are going to create a function that opens the array outside of the $.each() (I’d like to thank Viral Planet for their JavaScript Array Remove an Element post, helped me create this function with the added .name to allow searching by key name)

view plain

print?

01 function removeByValue(arr, val) {
02 for(var i=0; i<arr.length; i++) {
03 if(arr[i].name == val) {
04 arr.splice(i, 1);
05 break;
06 }
07 }
08 }
09 var names = ['Jim','Fred'];
10 $.each( names, function(i, v) {
11 removeByValue(myArray, v);
12 });

You can just use this function for removing a single item in the array too, I just wanted to show you a couple different ways. We can also update this function a bit and allow you to add the key name yourself.

view plain

print?

01 function removeByValue(arr, key, val) {
02 for(var i=0; i<arr.length; i++) {
03 if(arr[i][key] == val) {
04 arr.splice(i, 1);
05 break;
06 }
07 }
08 }
09 var names = ['Jim','Fred'];
10 $.each( names, function(i, v) {
11 removeByValue(myArray, 'name', v);
12 });

Enjoy