Home > Web Front-end > JS Tutorial > JavaScript Fun Questions: Ordered List

JavaScript Fun Questions: Ordered List

黄舟
Release: 2017-01-22 14:50:33
Original
2071 people have browsed it

An ordered list is different from an unordered list. The elements stored in it are in an ordered state, such as increasing or decreasing. In many ordered list implementations, you will definitely not find an operation like addAfter, because it is one of the characteristics of unordered lists.

General ordered lists provide several basic operations:

1.add is used to add elements to the list and maintain its ordered state

2. The get operation is used to obtain the element at the specified index

3.length attribute or method to obtain the length of the list

Among these operations, add is the most important part, and its implementation usually consists of 3 parts Composition (taking increasing sequence as an example):

1. Traverse the list from left to right until an element greater than or equal to the inserted value is found. At this time, the position of this element is the position to be inserted.

2. Move the element to the right of the insertion position one position backward

3. Insert the value into the position

function SortedList() {  
    this.length = 0;  
    this.elementData = [];  
}  
  
SortedList.prototype.add = function(val) {  
    var array = this.elementData;  
    for(var i=0;i<array.length;i++){  
        if(val <= array[i]){  
            break;  
        }  
    }  
    for(var j=array.length-1;j>=i;j--){  
        array[j+1] = array[j];  
    }  
    array[i] = val;  
    this.length++;  
}  
  
SortedList.prototype.get = function(i) {  
    return this.elementData[i];  
}
Copy after login

The above is an interesting JavaScript question: the content of an ordered list, For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template