Популярное

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

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

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

Топ запросов

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

JavaScript array mutators

Автор: kudvenkat

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

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

Описание:

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

JavaScript array mutators

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

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

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

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

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

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

JavaScript array filter method

JavaScript array filter method

Private members in JavaScript

Private members in JavaScript

🪏 УКРАИНУ ХОРОНЯТ НА ДАВОСЕ: напор Трампа, очки Макрона и Зе в домике. Блекаутизм элитки - Мосийчук

🪏 УКРАИНУ ХОРОНЯТ НА ДАВОСЕ: напор Трампа, очки Макрона и Зе в домике. Блекаутизм элитки - Мосийчук

Титульный Вторник | 20.01.2026 | Дебюты и Гамбиты

Титульный Вторник | 20.01.2026 | Дебюты и Гамбиты

JavaScript Tutorial

JavaScript Tutorial

Лижут ли Вас Собаки? ВОТ ЧТО ЭТО ЗНАЧИТ (вас шокирует)!

Лижут ли Вас Собаки? ВОТ ЧТО ЭТО ЗНАЧИТ (вас шокирует)!

5 операций, которые я, как врач, НИКОГДА бы не сделал! / Вы ПОЖАЛЕЕТЕ об ЭТИХ операциях!

5 операций, которые я, как врач, НИКОГДА бы не сделал! / Вы ПОЖАЛЕЕТЕ об ЭТИХ операциях!

Умер экс-министр финансов Беларуси / Реакция Лукашенко на серьезную беду: что не так?

Умер экс-министр финансов Беларуси / Реакция Лукашенко на серьезную беду: что не так?

Произойдет ли раскол между США и ЕС из-за конфликта вокруг Гренландии

Произойдет ли раскол между США и ЕС из-за конфликта вокруг Гренландии

ОБЫЧНЫЙ VPN УМЕР: Чем обходить блокировки в 2026

ОБЫЧНЫЙ VPN УМЕР: Чем обходить блокировки в 2026

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Я Построил Молот Высокого Давления

Я Построил Молот Высокого Давления

Почему БЫСТРАЯ ЗАРЯДКА быстро заряжает?

Почему БЫСТРАЯ ЗАРЯДКА быстро заряжает?

Где начало СХЕМЫ? Понимаем, читаем, изучаем схемы. Понятное объяснение!

Где начало СХЕМЫ? Понимаем, читаем, изучаем схемы. Понятное объяснение!

Events in JavaScript

Events in JavaScript

КВН 2025 Кубок мэра Москвы

КВН 2025 Кубок мэра Москвы

Запечённый картофель по рецепту Жоэля Ребюшона

Запечённый картофель по рецепту Жоэля Ребюшона

JavaScript c Нуля - Курс для начинающих С ПРАКТИКОЙ (2025)

JavaScript c Нуля - Курс для начинающих С ПРАКТИКОЙ (2025)

Creating two dimensional array in javascript

Creating two dimensional array in javascript

ЧТО СКРЫВАЕТ ДНО БАЙКАЛА? Тайны самого глубокого озера

ЧТО СКРЫВАЕТ ДНО БАЙКАЛА? Тайны самого глубокого озера

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



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



Контакты для правообладателей: infodtube@gmail.com