push()和pop()函数怎么在JavaScript中使用-创新互联

push()和pop()函数怎么在JavaScript中使用?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

清丰ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!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'));  // 6
console.log(arr1); // [1, 2, 3, 4, 'A', 'B']
console.log(arr2.push());  // 3
console.log(arr2); // ["C", "B", "A"]

运行结果:

push()和pop()函数怎么在JavaScript中使用

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()); // 4
console.log(arr1); // [1, 2, 3]
console.log(arr1.length); // 3
// 数组为空时
console.log(arr2.length); // 0
console.log(arr2.copyPop()); // undefined
console.log(arr2); // []
console.log(arr2.length); // 0

运行结果:

push()和pop()函数怎么在JavaScript中使用

关于push()和pop()函数怎么在JavaScript中使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


当前文章:push()和pop()函数怎么在JavaScript中使用-创新互联
分享地址:http://csdahua.cn/article/dopgjo.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流