Top-office11.ru

IT и мир ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Array reverse javascript

Форум

Справочник

Поиск по форуму
Расширенный поиск
К странице.

Илья Кантор, 3 ноя 2008 — 14:07

reverse

Синтаксис

Описание, примеры

Данный метод изменяет исходный массив.
После его применения порядок элементов в массиве меняется на обратный.

Он возвращает ссылку на измененный массив.

Обратите внимание, никакого нового массива не создается. Изменяется сам массив arr и возвращается ссылка на измененный массив.

См. также

  • sort /Метод/

Не повторяйте моей ошибки — я считал, что этот метод сортирует массив по убыванию. На самом деле, он просто меняет порядок следования элементов на противоположный.

А я вообще всегда думал, что reverse() генерирует новый массив и возвращает ссылку на него, а старый остаётся без изменений. Если бы не JS-консоль и мой гениальный моск, я бы так и дальше думал.

но всё же, почему разработчики так не сделали? к примеру, хотелось бы делать так:

Это фишка производительности или что?
В текущем существующем случае для получения вышеописанного метода приходится делать так:

Что мешает расширить прототип?

Прототипы — сила. Можно еще reverse() для String задать:

ошибка в последней строке
>);
надо убрать скобку перед ;

Илья спасибо за подробное объяснение, все это работает, а как насчет например если -123? чтобы вернуло -321?
вот мой код
var x = 123;
var reverse = function (x) <
var n = x.toString();
var rev = [];
for (var i = n.length-1; i >=0; i—) <
rev+=n[i]
>
return parseInt(rev)

ФУНКЦИЯ ВОЗВРАЩАЕТ ЗНАЧЕНИЕ — ЗНАЧИТ ПРОСТОЙ ЕЕ ВЫЗОВ НИЧЕГО НЕ ДАСТ!!
НАДО ПРИСВОИТЬ ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ ПЕРЕМЕННОЙ. Т.Е

а потом распечатать

и не обязательно в функции обьявлять переменную rev как массив,
так как вместо числа фунция вернет не число, а массив, что не есть хорошо.

т.е. окончательно код функции вместе с ее вызовом будет такая

var x = 123;
var reverse = function (x) <
var n = x.toString();
var rev = «»;
for (var i = n.length-1; i >=0; i—) rev+=n[i];
return parseInt(rev);
>
document.write(x+»»);
y=reverse(x);
document.write(y+»»);

Могёт кто нибудь подсказать зачем нужны скобки у reverse()

потому что это метод, а не свойство ))

Отправить комментарий

Поиск по сайту
Содержание

Учебник javascript

Основные элементы языка

Сундучок с инструментами

Интерфейсы

Все об AJAX

Оптимизация

Разное

Последние комментарии
  • This article is nice. I like it. Thank.
    16 часов 24 минуты назад
  • Thank you for such a well written.
    17 часов 56 минут назад
  • If you set out to make me think today;.
    17 часов 56 минут назад
  • I really enjoyed reading this post, big.
    1 день 4 часа назад
  • Superbly written article, if only all.
    1 день 4 часа назад
  • this is really nice to read.
    1 день 4 часа назад
  • i read a lot of stuff and i found that.
    1 день 4 часа назад
  • Waow this is quite pleasant article, my.
    1 день 20 часов назад
  • Intriguing post. I Have Been pondering.
    1 день 20 часов назад
  • Most of the time I don’t make comments.
    1 день 20 часов назад
Последние темы на форуме
Но если мы, к примеру, хотим запустить видео автоматически и без звука, фрейм будет таким: Как вы могли заметить к ссылке были добавлены необязательные параметры ?autoplay=0&mute=1 их мы и передаем в setting при использовании скрипта:

How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using array s, and I want to add a function that the user can reverse the list. I can’t think of any possible method, so if anybody knows how, please help.

30 Answers 30

Javascript has a reverse() method that you can call in an array

Not sure if that’s what you mean by ‘libraries you can’t use’, I’m guessing something to do with practice. If that’s the case, you can implement your own version of .reverse()

Do note that the built-in .reverse() method operates on the original array, thus you don’t need to reassign a .

Heres a functional way to do it.

20 bytes

This is what you want:

Above will reverse your array but modifying the original. If you don’t want to modify the original array then you can do this:

Here is a version which does not require temp array.

The shortest reverse method I’ve seen is this one:

Shortest reverse array method without using reverse method:

a.pop method takes an last element off and puts upfront with spread operator ()

MDN links for reference:

Using .pop() method and while loop.

I’ve made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.

Reverse by using the sort method

  • This is a much more succinct method.

As others mentioned, you can use .reverse() on the array object.

However if you care about preserving the original object, you may use reduce instead:

53 bytes

Just for fun, here’s an alternative implementation that is faster than the native .reverse method.

Using ES6 rest operator and arrow function.

Pure functions to reverse an array using functional programming:

It can also be achieved using map method.

Or using reduce (little longer approach)

I’m not sure what is meant by libraries, but here are the best ways I can think of:

What about without using push() !

Solution using XOR !

JavaScript already has reverse() method on Array, so you don’t need to do that much!

Imagine you have the array below:

Now simply just do this:

and you get this as the result:

But this basically change the original array, you can write a function and use it to return a new array instead, something like this:

Or simply chaning JavaScript built-in methods for Array like this:

and you can call it like this:

Just as mentioned, the main difference is in the second way, you don’t touch the original array.

How to Reverse Arrays in JavaScript Without Using .reverse()

In-Place & Out-of-Place

A typical JavaScript challenge or interview question has to do with reversing arrays in-place and out-of-place. Specifically, take this problem from Eloquent JavaScript, 2nd Edition:

That’s the kicker: you can’t use the .reverse() method.

I worked through this problem in the past, but now that I am getting back to studying JavaScript after a break, it took me awhile to re-wrap my head around it. Especially reversing the array in-place. To help me better understand and think through this problem I decided to write this article.

Reversing an Array Out-of-Place

To start, let’s make up two arrays:

For the reverseArray function, if we’re going to produce a new array we need an empty array to fill up later:

Writing the steps out in pseudo-code:

Let’s come up with our for loop first. To start at the end of the array we want to set i equal to the length of the array minus 1, since the index of an array always starts at zero.

For example, array1.length would give us 7 because there are seven elements in it. The index of each, however, is 0, 1, 2, 3, 4, 5, and 6. So in order to begin at the element with an index of 6 we’d need to take the length of the array and subtract 1.

Writing out our full for loop we get:

In other words, we are subtracting 1 from the index with each loop until i is greater than or equal to 0, the beginning of the array. (Using arr as the parameter name in the below function is the same as using array . Don’t let that throw you!)

arr[i] represents each element at its respective index. On the first loop through, arr[i] is the element «if» . On each loop we use the .push() method to literally ‘push’ arr[i] to the end of the newArray .

Passing array1 into this function we’d get:

Reversing an Array In-Place

Things immediately get more complicated for me when trying to reverse an array in-place. When I initially tried working through this problem I was trying to grab the first element using .shift() , setting that to a variable named first , then using .push() to add it to the end of the original array. But the problem I ran into is that I was just reversing the first and last elements over and over again with each loop, because .shift() only removes elements at the ‘zeroeth index’ and .pop() at the last.

There was also the problem of where to start and end the for loop.

Before going further, though, let’s write out the problem in pseudo-code:

So in terms of our for loop, I can start at the beginning or the end of the array, and finish when i is half the length of the array.

The way I initially thought to do this was:

I then set the first element equal to a variable called el , then set the first element equal to the last, and the last equal to the first ( el ).

Here’s how it looks:

So with each loop, el would be reset to equal the next element in the array.

arr[arr.length — 1 — i] is just a way of saying:

  1. On the first loop, the index is the length of the array, minus 1, minus the value of i , which is 0. Using array1 as an example, it would be: 8 — 1 — 0 = 7 . arr[7] is the last element of array1 , which is «if» .
  2. On the second loop, it would be: 8 — 1 — 1 = 6 . Therefore, arr[6] would be the second-to-last element of array1 , which is «never» . On and on until reaching the m >Attempting it this way, it looks like:

But in testing this, something odd happens with arrays that have an even length, such as array2 :

9 and 5 are reversed in the middle!

In cases where our array is an odd number, like array1 , using i would work, because array1.length is 3.5, and the loop would continue as long is i is less than or equal to 3.5. But if our length is 8, as it is in array2 , then the loop will stop at index 4, which is actually 1 index past where we want to stop. Because the index starts at 0, we actually want to stop at 3.

To fix this we can subtract 1 from the length of the array before div >Math.floor in front to round decimals down to the nearest whole number.

To review:

  • We started at the beginning of the array in our for loop.
  • We moved through the array until we reached the halfway point.
  • With each loop we set the element at i — or arr[i] — equal to a variable called el .
  • Then we set the first element equal to the last, and the last element equal to the first.
  • With each subsequent loop, as we moved inward we did the same thing.

I’m a JavaScript rookie, so if you have a more efficient way of doing this I’d love to hear from you in the comments section below!

Three Ways to Reverse a String in JavaScript

Sonya Moisset

✈️ ☕️ ️ Lead Security Engineer @Photobox | Tech Lead/Security Manager@PrideInLondon | Tech Advocate

This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

Reversing a string is one of the most frequently asked JavaScript question in the technical round of interview. Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-built methods, or they may even ask you to reverse a string using recursion.

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.

Algorithm Challenge

Reverse the provided string.
You may need to turn the string into an array before you can reverse it.
Your result must be a string.

Provided test cases

  • reverseString(“hello”) should become “olleh”
  • reverseString(“Howdy”) should become “ydwoH”
  • reverseString(“Greetings from Earth”) should return”htraE morf sgniteerG”

1. Reverse a String With Built-In Functions

For this solution, we will use three methods: the String.prototype.split() method, the Array.prototype.reverse() method and the Array.prototype.join() method.

  • The split() method splits a String object into an array of string by separating the string into sub strings.
  • The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
  • The join() method joins all elements of an array into a string.

Chaining the three methods together:

2. Reverse a String With a Decrementing For Loop

Without comments:

3. Reverse a String With Recursion

For this solution, we will use two methods: the String.prototype.substr() method and the String.prototype.charAt() method.

  • The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
  • The charAt() method returns the specified character from a string.

The depth of the recursion is equal to the length of the String. This solution is not the best one and will be really slow if the String is very long and the stack size is of major concern.

Without comments:

Conditional (Ternary) Operator:

Reversing a String in JavaScript is a small and simple algorithm that can be asked on a technical phone screening or a technical interview. You could take the short route in solving this problem, or take the approach by solving it with recursion or even more complex solutions.

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below 😉

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

Resources

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Читать еще:  Visual studio отладка javascript
Ссылка на основную публикацию
Adblock
detector