Let's go to work without saying much. In this post, we will get acquainted with the methods of arrays in the javascript programming language and work on related issues.
Add element, change.
- length()
- push()
- concat()
Turn off.
- pop()
- shift()
- splice()
- delete array[i]
search
- find(function())
- indexOf()
Arrange
- sort() for numbers and for strings
Reverse
- reverse()
Add and modify items.
Thelength method finds the number of elements, or the length, of the array.
It should be noted that the type of arrays in Javascript is object. If you have learned languages like c/c or java before, this may seem a bit confusing. In JavaScript, arrays themselves are actually data-type , which is different from arrays in c/c. In JS, you can store different types of data in one array.
// Arrayning uzunligi, o'lchami const array = ["nimadir", "kimdir", true, 55, 4.6]; console.log(`arrayning uzunligi ${array.length}`);
Add a new element from the end of an array.
You may have a question. Is it possible to change the value of a constant variable? Yes, we are inserting a new element through the push() method, but we are not setting a new value to the array.
// push(), array oxiriga yangi element qo'shish const array = ["nimadir", "kimdir", true, 55, 4.6]; array.push("yangi element"); console.log(`arrayning uzunligi: ${array} \n`);
Combine two arrays (concatenate).
concat() method will combine two arrays.
// concat(), ikki arrayni birlashtirish let array1 = ["nimadir", "kimdir", true, 55, 4.6]; let array2 = [8, 3, 9]; console.log("array1: " + array1, "\n", "array2: " + array2 + "\n"); let result = array1.concat(array2); console.log( `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n` );
Deleting an element from an array.
There are several different ways to delete array elements in JavaScript.
pop() method is used to remove one element from the end of the array.
// pop(), arrayning oxiridan bitta element o'chiradi let array1 = [6, "satr", true, 55, 4.6]; console.log(`\navval: [${array1}]\n`); array1.pop(); console.log(`keyin: [${array1}]\n`);
The
shift() method removes one element from the beginning of the array
// shift() Metodi const array = [44, 5.3, 2, 14, 98, "text", "olma"]; console.log(`\navval: [${array}] \n`); array.shift(); console.log(`keyin: 44 arrayda emas [${array}]\n`);
The
splice() method is unique in that it is not only used to delete elements, but also to modify data. For deletion purposes, the method takes two values.
- first: is the starting index for deleting elements.
- second: how many elements to delete.
For example: const array = [44, 5.3, 2, 14, 98, "text", "apple"]; there is. We want to delete 2 elements, starting from index 3, i.e. 14 (14 itself is deleted), 2 elements.
// Arrayning uzunligi, o'lchami const array = ["nimadir", "kimdir", true, 55, 4.6]; console.log(`arrayning uzunligi ${array.length}`);
For the purpose of replacement, splice() is used as follows.
- start index array.splice(3, ...)
- how many elements to swap array.splice(3, 2, ...)
- new elements to be inserted accordingly array.splice(3, 2, "new1", "new2")
// push(), array oxiriga yangi element qo'shish const array = ["nimadir", "kimdir", true, 55, 4.6]; array.push("yangi element"); console.log(`arrayning uzunligi: ${array} \n`);
The
delete array[i] method is the easiest way to delete an array element. In this case, the index of the element to be deleted is written instead of [i].
// concat(), ikki arrayni birlashtirish let array1 = ["nimadir", "kimdir", true, 55, 4.6]; let array2 = [8, 3, 9]; console.log("array1: " + array1, "\n", "array2: " + array2 + "\n"); let result = array1.concat(array2); console.log( `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n` );
Searching from an array
Thefind(function()) method is used to search for a given element from an array. A function is written to this method as a value, and the function is given the element to search for. The function does not return an index, if the searched element is present in the array, it returns this element, otherwise it returns undefined.
// pop(), arrayning oxiridan bitta element o'chiradi let array1 = [6, "satr", true, 55, 4.6]; console.log(`\navval: [${array1}]\n`); array1.pop(); console.log(`keyin: [${array1}]\n`);
indexOf() method returns the index of the searched element.
// shift() Metodi const array = [44, 5.3, 2, 14, 98, "text", "olma"]; console.log(`\navval: [${array}] \n`); array.shift(); console.log(`keyin: 44 arrayda emas [${array}]\n`);
Arrange
sort() method, this is where JavaScript's "headache" begins. At first glance, the sort() method looks simple, but there is actually another process going on behind the scenes. By default, sort() sorts strings , but can sort correctly if an integer or numeric value is given. But JavaScript sorts numbers if it wants to, not if it doesn't (just kidding):)
// splice() Metodi const array = [44, 5.3, 2, 14, 98, "text", "olma"]; console.log(`\navval: [${array}] \n`); array.splice(3, 2); console.log(`keyin: 14 va 98 elementlari o'chdi [${array}]\n`);
in numerical values as follows.
// splice() Metodi const array = [44, 5.3, 2, 14, 98, "text", "olma"]; console.log(`\navval: [${array}] \n`); array.splice(3, 2, "yangi1", "yangi2"); console.log(`keyin: 14 va 98 elementlari almashtirildi [${array}]\n`);
So what's the problem?
You can say, let's continue.
// Arrayning uzunligi, o'lchami const array = ["nimadir", "kimdir", true, 55, 4.6]; console.log(`arrayning uzunligi ${array.length}`);
Stop, look at the result, sorted array: [100,1021,30,45,61,8] what's that!?
JavaScript sorts an array as a string. Even if a number is given, it will be transferred to ascii code and sorted lexicographically, i.e. like a string. This will cause an error. In the problem, 100 should be the last number, and 30 should be before 100. as a char, 1 precedes 3, so an error occurs (see ascii table!). To fix this, we give function() to the sort() method.
// push(), array oxiriga yangi element qo'shish const array = ["nimadir", "kimdir", true, 55, 4.6]; array.push("yangi element"); console.log(`arrayning uzunligi: ${array} \n`);
The functionarray.sort((a, b) => a - b); compares two elements in an array and determines their order.
- a and b: These are the two elements from the array that are compared. The sort() method compares all elements pairwise (for example, a and b) and arranges them according to the result of the comparison function.
- a - b: By calculating these differences, the order of the elements is determined:
- If a - b is negative (ie, a
- If a - b is positive (ie, a > b), b precedes a.
- If a - b is zero (ie, a === b), then they are not mutually exclusive.
Result:
Flipping
Thereverse() method creates an array that is the reverse of the array given by its name.
// concat(), ikki arrayni birlashtirish let array1 = ["nimadir", "kimdir", true, 55, 4.6]; let array2 = [8, 3, 9]; console.log("array1: " + array1, "\n", "array2: " + array2 + "\n"); let result = array1.concat(array2); console.log( `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n` );
Result:
I hope you have gained knowledge about JavaScript array methods through this post, share this post with your loved ones who are learning JS!
Questions to review:
1. Add element, change:
a. length()
Problem: Imagine a large array containing 1000 values. If you only need to output the number of elements in an array, what method would you use? How does the number of elements change with any changes to the array?
Problem: If you need to add 1000 new elements to the end of a given array, determine the length of the array. Which method is the most effective to use for this?
b. push()
Problem: You have an array where every element is the same. Every time you add a new element, you must replace the element at the end of the array. How do you optimize these operations?
Problem: You have an array called tasks that contains various tasks that need to be performed. Each time you need to add a new task and update the task at the end of the list. How do you do this?
c. concat()
Problem: You need to merge two arrays and display them in the same format. The first array contains only simple numbers, and the second contains only numeric strings. How to create a new array from them and output all the numbers in numeric format?
Problem: You have two arrays, one containing information about users and the other containing the login history of users. You need to merge these arrays, but you only want to display the active state histories of the users. How do you do this?
2. Delete:
a. pop()
Problem: You have multiple user lists, and each time you need to remove the last user from the list. But you only want to keep active users from the last 3 days. How can you manage them?
Problem: You have an array named books that contains information about various books. Each time you need to delete the last book and add a new book. How do you do it?
b. shift()
Problem: Imagine a queue process where users are waiting for their turn. Each time you log out of the next user and enter a new user. How do you do this process?
Problem: You have an array organized by user login time. You must unsubscribe the very first user each time. How do you do this?
c. splice()
Problem: You have a list of students and each time you need to change or remove 3 students from the list. How do you do this process?
Problem: You have a list of issues. Each time several issues need to be removed and changed. When changing an issue, the other issues must remain in the correct order. How do you do this?
d. delete array[i]
Problem: You have a large array, and you need to delete an element based on its index. What should be done when deleting an element, taking into account how other elements in the array are changed?
Problem: You have a list of customers and each customer has a unique ID number. What method can be used to unregister a customer for a given ID?
3. Search:
a. find(function())
Problem: You have a list of users. Each user has an ID number and a name. You only need to get the information of the user whose name is "John". How do you do this?
Problem: You have a list of products, and each product has a name and a price. You only need to look for products with a price above 100. How do you do this?
b. indexOf()
Problem: You have a list of books, and each book has a title and an author. If the user searches for a book, determine which index it is in by name.
Problem: You have a list of products and each product is assigned a unique identification number. If a user is looking for a product, you should be able to find it based on its ID number. How is this done?
4. Order:
a. sort()(for numbers)
Problem: You have multiple student ratings. Sort grades from lowest to highest, but sort students with the same grade by name.
Problem: You have an array containing the prices of products. You can sort the prices in descending order, but if the prices are the same, sort them by sale date.
b. sort()(for strings)
Problem: You have an array of customer names. You should sort them alphabetically, but only by uppercase
Problem: You have the titles of the books. You want to sort all the books by the length of the words in them. How do you do this?
5. Click:
a. reverse()
Problem: You have an array of multiple numbers. You must output this array in reverse order. How to calculate the changes of this?
Problem: You have a list of texts and you want to output the texts in reverse order. What would you get if the texts were all the same length?
bugs and questions
The above is the detailed content of JavaScript array methods.. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
