JavaScript中push()和pop()方法如何使用

这篇文章给大家介绍JavaScript中push()和pop()方法如何使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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;};console.log(arr1.push('A', 'B'));  // 6console.log(arr1); // [1, 2, 3, 4, 'A', 'B']console.log(arr2.push());  // 3console.log(arr2); // ["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;};console.log(arr1.copyPop()); // 4console.log(arr1); // [1, 2, 3]console.log(arr1.length); // 3// 数组为空时console.log(arr2.length); // 0console.log(arr2.copyPop()); // undefinedconsole.log(arr2); // []console.log(arr2.length); // 0

关于JavaScript中push()和pop()方法如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。