Home > Article > Web Front-end > JavaScript Fun Questions: Ordered List
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]; }
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 (www.php.cn)!