Use Javascript to move up and down elements in an array

Source: Internet
Author: User
This article describes how to move up and down elements in an array using Javascript. The sample code in this article is very detailed and has some reference and learning value for everyone, let's take a look. This article describes how to move up and down elements in an array using Javascript. The sample code in this article is very detailed and has some reference and learning value for everyone, let's take a look.

Preface

We can change the array to move the elements up and down. This effect is used in tables or previous sorting algorithms. Here is an example of how to move the elements up and down in the exchange array in JavaScript.

When writing a project, you need to implement an example of moving up and down Array records. There is no trouble in writing it. It is nothing more than exchanging array elements. The final implementation code is as follows. What is more important is the function.

Sample Code:

// Exchange array element var swapItems = function (arr, index1, index2) {arr [index1] = arr. splice (index2, 1, arr [index1]) [0]; return arr ;}; // move up $ scope. upRecord = function (arr, $ index) {if ($ index = 0) {return;} swapItems (arr, $ index, $ index-1 );}; // move down $ scope. downRecord = function (arr, $ index) {if ($ index = arr. length-1) {return;} swapItems (arr, $ index, $ index + 1 );};

By using this method properly, you can achieve top-level and bottom-level implementations.

The preceding section describes how to use Javascript to move up and down elements in an array. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.