ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

JavaScript array mutators

Автор: kudvenkat

Загружено: 2014-12-20

Просмотров: 77916

Описание: Link for all dot net and sql server video tutorial playlists
   / kudvenkat  

Link for slides, code samples and text version of the video
http://csharp-video-tutorials.blogspo...

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
   / @aarvikitchen5572  

There are several methods that can be used with the array object in JavaScript. Some methods modify the array object while the others do not. The methods that modify the array object are called as mutator methods.

The following are the examples of non-mutator methods
contains
indexOf
lastIndexOf

The following are the examples of mutator methods
push
pop
shift
unshift
reverse
sort
splice

We discusssed push(), pop(), shift() and unshift() methods in Part 20. In this video we will discuss
sort
reverse
splice

JavaScript sort method : Sorts the elements of an array. By default, the sort() method sorts the values by converting them to strings and then comparing those strings. This works well for strings but not for numbers. Let us look at an example.

Example : Notice that the strings are sorted correctly as expected.

var myArray = ["Sam","Mark","Tom","David"];
myArray.sort();
document.write(myArray);

Output : David,Mark,Sam,Tom

Now, let's look at an example of sorting numbers.

var myArray = [20, 1 , 10 , 2, 3];
myArray.sort();
document.write(myArray);

Output : 1,10,2,20,3

Notice that the numbers are not sorted as expected. We can fix this by providing a "compare function" as a parameter to the sort function. The compare function should return a negative, zero, or positive value.

Example :

var myArray = [20, 1, 10, 2, 3];
myArray.sort(function (a, b) { return a - b });
document.write(myArray);

Output : 1,2,3,10,20

Let's now discuss how the compare function work. The function has 2 parameters (a,b). This function subtracts a from b and returns the result. If the return value is
Positive - a is a number bigger than b
Negative - a is a number smaller than b
ZERO - a is equal to b

So, based on these return values, the numbers in the array are sorted.

Sorting the numbers in descending order : There are 2 ways to sort an array in descending order

1. Return (b-a) from the compare function instead of (a-b)

Example :

var myArray = [20, 1, 10, 2, 3];
myArray.sort(function (a, b) { return b - a });
document.write(myArray);

Output : 20,10,3,2,1

2. Sort the numbers first in ascending order and then use the reverse function to reverse the order of the elements in the array.

Example :

var myArray = [20, 1, 10, 2, 3];
myArray.sort(function (a, b) { return a - b }).reverse();
document.write(myArray);

Output : 20,10,3,2,1

JavaScript reverse method : reverses the order of the elements in an array.

JavaScript splice method : This method is used to add or remove elements from an array.

Syntax : array.splice(index,deleteCount,item1,.....,itemX)

index - Required. Specifies at what position to add or remove items
deleteCount - Required. The number of items to be removed. If set to 0, no items will be removed.
item1,.....,itemX - Optional. The new item(s) to be added to the array

Example :

var myArray = [1,2,5];
myArray.splice(2, 0, 3, 4);
document.write(myArray);

Output : 1,2,3,4,5

Example :

var myArray = [1,2,55,67,3];
myArray.splice(2, 2);
document.write(myArray);

Output : 1,2,3

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
JavaScript array mutators

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

JavaScript array filter method

JavaScript array filter method

Events in JavaScript

Events in JavaScript

Private members in JavaScript

Private members in JavaScript

Converting strings to numbers in JavaScript

Converting strings to numbers in JavaScript

Bossa Nova Jazz - Best Bossa Nova Covers 2025 for a Relaxing Vibe

Bossa Nova Jazz - Best Bossa Nova Covers 2025 for a Relaxing Vibe

Deep House Winter Mix 2026 ❄️ Chill & Mix - Best Of Chill Out Sessions by Deep Paradise

Deep House Winter Mix 2026 ❄️ Chill & Mix - Best Of Chill Out Sessions by Deep Paradise

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

JavaScript timing events

JavaScript timing events

Понимание Active Directory и групповой политики

Понимание Active Directory и групповой политики

ДНК создал Бог? Самые свежие научные данные о строении. Как работает информация для жизни организмов

ДНК создал Бог? Самые свежие научные данные о строении. Как работает информация для жизни организмов

Успокаивает, восстанавливает нервную систему 🌿 Перестаньте думать, музыка для снятия стресса #4

Успокаивает, восстанавливает нервную систему 🌿 Перестаньте думать, музыка для снятия стресса #4

Different ways of defining functions in JavaScript

Different ways of defining functions in JavaScript

Czy Putin chce pokoju? Kulisy decyzji na Kremlu | prof. Hieronim Grala | ŻEBY WIEDZIEĆ #9

Czy Putin chce pokoju? Kulisy decyzji na Kremlu | prof. Hieronim Grala | ŻEBY WIEDZIEĆ #9

Создавайте лучшие веб-приложения с Blazor в .NET 10

Создавайте лучшие веб-приложения с Blazor в .NET 10

Static members in JavaScript

Static members in JavaScript

Ariana Grande, Mariah Carey, Justin Bieber, Christmas Songs Christmas Songs Playlist 2026

Ariana Grande, Mariah Carey, Justin Bieber, Christmas Songs Christmas Songs Playlist 2026

Исследовательский анализ данных с помощью Pandas Python

Исследовательский анализ данных с помощью Pandas Python

Assigning event handlers in JavaScript using DOM object property

Assigning event handlers in JavaScript using DOM object property

ВОССТАНОВЛЕНИЕ НЕРВНОЙ СИСТЕМЫ 🌸 Нежная музыка, успокаивает нервную систему и радует душу #6

ВОССТАНОВЛЕНИЕ НЕРВНОЙ СИСТЕМЫ 🌸 Нежная музыка, успокаивает нервную систему и радует душу #6

Working with dates in javascript

Working with dates in javascript

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]