Home  >  Article  >  Web Front-end  >  js simulates a simple example of List in C#_javascript skills

js simulates a simple example of List in C#_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:56:441216browse

复制代码 代码如下:

/*
 * List 大小可变数组
 * version: 1.0
 */
function List() {
    this.list = new Array();
};

/**
* Add the specified element to the end of this list.
* @param object specified element
*/
List.prototype.add = function(object) {
    this.list[this.list.length] = object;
};

/**
* Add List to the end of this list.
* @param listObject a list
*/
List.prototype.addAll = function(listObject) {
    this.list = this.list.concat(listObject.list);
};

/**
* Returns the element at the specified position in this list.
* @param index specifies the position
* @return the element at this position
*/
List.prototype.get = function(index) {
    return this.list[index];
};

/**
* Remove the element at the specified position from this list.
* @param index specifies the position
* @return the element at this position
*/
List.prototype.removeIndex = function(index) {
    var object = this.list[index];
    this.list.splice(index, 1);   
    return object;
};

/**
* Remove the specified element from this list.
* @param object specified element
* @return element at this position
*/
List.prototype.remove = function(object) {
    var i = 0;
    for(; i < this.list.length; i ) {       
        if( this.list[i] === object) {
            break;
        }       
    }
    if(i >= this.list.length) {
        return null;
    } else {
        return this.removeIndex(i);
    }
};

/**
* Remove all elements from this list.
*/
List.prototype.clear = function() {
    this.list.splice(0, this.list.length);
};

/**
* Returns the number of elements in this list.
* @return the number of elements
*/
List.prototype.size = function() {
    return this.list.length;
};

/**
* Returns a list between start (inclusive) and end (exclusive) specified in the list.
* @param start starting position
* @param end ending position
* @return new list
*/
List.prototype.subList = function(start, end) {   
    var list = new List();
    list.list = this.list.slice(start, end);
    return list;
};

/**
* Returns true if the list contains no elements.
* @return true or false
*/
List.prototype.isEmpty = function() {
    return this.list.length == 0;
};

Statement:
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