Home > Web Front-end > JS Tutorial > body text

Introduction to the use of js secondary encapsulation array (code)

不言
Release: 2018-07-25 10:01:50
Original
1353 people have browsed it

The content shared with you in this article is about the secondary encapsulation of our array by JS data structure. The content is very detailed. Next, let’s take a look at the specific content. I hope it can help everyone.

1. Create a new myArray class

class myArray {
    
}
Copy after login

2. Initialize the constructor on this class

/**
 * 初始化构造函数
 * @param capacity 容量
 */
constructor(capacity) {
    // 初始化arr变量
    this.arr = capacity === undefined ? [] : new Array(capacity);
    // 数组长度
    this.length = 0;
    // 数组容量
    this.capacity = capacity;
}
Copy after login

3. Add array member method

// 获取数组的长度
getLength() {
    return this.length;
}

// 获取数组的容量
getCapacity() {
    return this.arr.length;
}

// 判断数组是否为空
isEmpty() {
    return this.length === 0;
}
Copy after login

4. Method of adding elements to an array

/**
 * 在数组中在index插入一个新的元素e
 * @param index 索引
 * @param e 元素
 * 原理:
 * 首先在传进来index索引的位置向后面移动一位,
 * 然后把该index索引腾空出来放进传入的新的元素e,
 * 最后维护一下length,长度加1
 */
add(index, e) {

    if (this.length === this.arr.length) {
        throw new Error('Add failed. Array is full.')
    }

    if (index < 0 || index > this.length) {
        throw new Error('Add failed. Request index >= 0 and index <= length&#39;);
    }

    for (let i = this.length - 1; i >= index; i--) {
        this.arr[i + 1] = this.arr[i];
    }

    this.arr[index] = e;
    this.length++;
}


// 向数组首位添加一个新元素e
addFirst(e) {
    this.add(0, e)
}

// 向数组所有的元素后面添加一个新元素e
addLast(e) {
    this.add(this.length, e);
}
Copy after login

5. Methods of adding elements to an array

/**
 * 从数组中删除index位置的元素,返回删除的元素
 * @param index
 * @returns {*}
 * 原理:
 * 首先找到索引index的位置,
 * 然后把索引后面的元素都向前移动一位,其实是把索引后面的翻盖前面一位的元素
 * 最后维护一下length,减一
 *
 */
remove(index) {
    if (index < 0 || index >= this.length) {
        throw new Error('Remove failed. Request index >= 0 and index <= length');
    }

    let ret = this.arr[index];
    for (let i = index + 1; i < this.length; i++) {
        this.arr[i - 1] = this.arr[i];
    }
    this.length--;

    return ret;
}

// 从数组中删除第一个元素,返回删除的元素
removeFirst() {
    return this.remove(0)
}

// 从数组中删除最好个元素,返回删除的元素
removeLast() {
    return this.remove(this.length - 1)
}

// 从数组中删除元素e
removeElement(e) {
    let index = this.findIndex(e);
    if (index != -1) {
        this.remove(index);
    }
}
Copy after login

6. Methods of querying and modifying elements in an array

// 获取index索引位置的元素
get(index) {
    if (index < 0 || index >= this.length) {
        throw new Error('Get failed. Index is illegal.');
    }
    return this.arr[index];
}

// 修改index索引的元素e
set(index, e) {
    if (index < 0 || index >= this.length) {
        throw new Error('Get failed. Index is illegal.');
    }
    this.arr[index] = e;
}
Copy after login

7. Adding an array Contains, search method

// 查询数组是否包含e元素
contains(e) {
    for (let i = 0; i < this.length; i++) {
        if (this.arr[i] === e) {
            return true;
        }
    }
    return false;
}

// 查找数组中元素所在的所在的索引,如果不存在e,则返回-1
findIndex(e) {
    for (let i = 0; i < this.length; i++) {
        if (this.arr[i] === e) {
            return i;
        }
    }
    return -1;
}

// 把数组转换为字符串,并返回结果
toString() {
    let res = "";
    console.log(`Array: length = ${this.length}, capacity = ${this.capacity}.`);

    res += "[";
    for (let i = 0; i < this.length; i++) {
        res += this.arr[i];
        if (i !== this.length - 1) {
            res += ', '
        }
    }
    res += "]";

    return res.toString();
}
Copy after login

8. Method of testing encapsulated array

// 使用我们的类数组,声明一个容量为20的数组
let arr = new myArray(20);
// 首位增加数据
arr.addFirst('波波');
console.log(arr.toString());
// 输出:Array: length = 1, capacity = 20.
// 输出:[波波]

for (let i = 0; i < 10; i++) {
    arr.addLast(i)
}
console.log(arr.toString());
// 输出:Array: length = 11, capacity = 20.
// 输出:[波波, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(arr.findIndex(4)); // 5

// ...
Copy after login

9. Method description

##getLength Return the length of the arraygetLength()getCapacity Return the capacity of the arraygetCapacity()isEmpty Determine whether the array is empty and return a Boolean valueisEmpty()addFirstAdd a new element to the first element of the arrayeNew elementaddFirst(e)addLastAdd a new element after all elements of the arrayeNew elementaddLast(e)addInsert a new element at index in the array eindex, eindex index, e new elementadd(index, e) removeRemove the element at index position from the array and return the deleted elementindexIndexremove(index)removeFirstRemove the first element from the array and return the deleted elementremoveFirst()removeLastRemoves the last element from the array and returns the deleted elementremoveElementgetsetcontainsfindIndextoString10. Complete secondary encapsulation array code
class myArray {
    /**
     *  初始化构造函数
     * @param capacity 容量
     */
    constructor(capacity) {
        // 初始化arr变量
        this.arr = capacity === undefined ? [] : new Array(capacity);
        // 数组长度
        this.length = 0;
        // 数组容量
        this.capacity = capacity;
    }

    // 获取数组的长度
    getLength() {
        return this.length;
    }

    // 获取数组的容量
    getCapacity() {
        return this.arr.length;
    }

    // 判断数组是否为空
    isEmpty() {
        return this.length === 0;
    }

    addFirst(e) {
        this.add(0, e)
    }

    // 向所有的元素后面添加一个新元素
    addLast(e) {
        this.add(this.length, e);
    }

    /**
     * 在数组中在index插入一个新的元素e
     * @param index 索引
     * @param e 元素
     * 原理:首先在传进来index索引的位置向后面移动一位,
     * 然后把该index索引腾空出来放进传入的新的元素e,
     * 最后维护一下length,长度加1
     */
    add(index, e) {

        if (this.length === this.arr.length) {
            throw new Error('Add failed. Array is full.')
        }

        if (index < 0 || index > this.length) {
            throw new Error('Add failed. Request index >= 0 and index <= length');
        }

        for (let i = this.length - 1; i >= index; i--) {
            this.arr[i + 1] = this.arr[i];
        }

        this.arr[index] = e;
        this.length++;
    }

    /**
     * 从数组中删除index位置的元素,返回删除的元素
     * @param index
     * @returns {*}
     * 原理:
     * 首先找到索引index的位置,
     * 然后把索引后面的元素都向前移动一位,其实是把索引后面的翻盖前面一位的元素
     * 最后维护一下length,减一
     *
     */
    remove(index) {
        if (index < 0 || index >= this.length) {
            throw new Error('Remove failed. Request index >= 0 and index <= length');
        }

        let ret = this.arr[index];
        for (let i = index + 1; i < this.length; i++) {
            this.arr[i - 1] = this.arr[i];
        }
        this.length--;

        return ret;
    }

    // 从数组中删除第一个元素,返回删除的元素
    removeFirst() {
        return this.remove(0)
    }

    // 从数组中删除最好个元素,返回删除的元素
    removeLast() {
        return this.remove(this.length - 1)
    }

    // 从数组中删除元素e
    removeElement(e) {
        let index = this.findIndex(e);
        if (index != -1) {
            this.remove(index);
        }
    }


    // 获取index索引位置的元素
    get(index) {
        if (index < 0 || index >= this.length) {
            throw new Error('Get failed. Index is illegal.');
        }
        return this.arr[index];
    }

    // 修改index索引的元素e
    set(index, e) {
        if (index < 0 || index >= this.length) {
            throw new Error('Get failed. Index is illegal.');
        }
        this.arr[index] = e;
    }

    // 查询数组是否包含e元素
    contains(e) {
        for (let i = 0; i < this.length; i++) {
            if (this.arr[i] === e) {
                return true;
            }
        }
        return false;
    }

    // 查找数组中元素所在的所在的索引,如果不存在e,则返回-1
    findIndex(e) {
        for (let i = 0; i < this.length; i++) {
            if (this.arr[i] === e) {
                return i;
            }
        }
        return -1;
    }

    // 把数组转换为字符串,并返回结果
    toString() {
        let res = "";
        console.log(`Array: length = ${this.length}, capacity = ${this.capacity}.`);

        res += "[";
        for (let i = 0; i < this.length; i++) {
            res += this.arr[i];
            if (i !== this.length - 1) {
                res += ', '
            }
        }
        res += "]";

        return res.toString();
    }
}

// 测试
// 使用我们的类数组,声明一个容量为20的数组
let arr = new myArray(20);
// 首位增加数据
arr.addFirst('波波');
console.log(arr.toString());
// 输出:Array: length = 1, capacity = 20.
// 输出:[波波]

for (let i = 0; i < 10; i++) {
    arr.addLast(i)
}
console.log(arr.toString());
// 输出:Array: length = 11, capacity = 20.
// 输出:[波波, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(arr.findIndex(4)); // 5

// ...上面的方法都可以测试使用。
Copy after login
Method Description Parameters Parameter description Example










##removeLast()
Remove elements from the array e e Deleted element e removeElement(e)
Get the element at the index index position index Index get(index)
Modify the element of index index e index, e index index, e newly replaced element set(index, e)
Query array Whether the e element is included e Query the contained elements contains(e)
Find The index where element e is located in the array. If e does not exist, -1 is returned. e The element queried findIndex(e)
Return array formatted data
##toString()
Related recommendations:

Modular analysis of js (namespace)

What is a JS variable object? Detailed explanation of JS variable objects and precautions

The above is the detailed content of Introduction to the use of js secondary encapsulation array (code). For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!