数组方法实现(二)————数组方法push()、pop()

来源:互联网 发布:vip域名是哪个国家的 编辑:程序博客网 时间:2024/06/05 06:22

push()方法

1. 定义:向数组的末尾添加一个或更多元素,并返回新的长度。2. 语法: arr.push(element1, ..., elementN)3. 参数:可以接收任意个数量的参数4. 返回值:返回修改后数组的长度。
var arr1 = [1, 2, 3, 4]; var arr2 = ["C", "B", "A"];Array.prototype.copyPush = function() {    for(var i = 0; i < arguments.length; i++) {        this[this.length] = arguments[i];    }    return this.length;};arr1.push('A', 'B');   // 6arr1; // [1, 2, 3, 4, 'A', 'B']arr2.push();   // 3arr2;  // ["C", "B", "A"]

pop()方法

1. 定义:从数组末尾移除最后一项,减少数组的length值,并返回移除的项。2. 语法: arr.pop()3. 参数:/4. 返回值:从数组中删除的元素(当数组为空时返回undefined)。
var arr1 = [1, 2, 3, 4];var arr2 = [];Array.prototype.copyPop = function() {    var result = null;    if(this.length == 0) { //数组为空时返回undefined        return undefined;    }    result = this[this.length - 1];    this.length = this.length - 1;    return result;};arr1.copyPop(); // 4arr1; // [1, 2, 3]arr1.length; // 3// 数组为空时arr2.length; // 0arr2.copyPop(); // undefinedarr2; // []arr2.length; // 0
阅读全文
0 0