数组常用方法(1).html

<script type="text/javascript">
//数组常用方法1(只能是数组使用)

var arr=[1,2,3,4,5]

//1.push() 向数组中添加数据
//语法 数组.push(需要添加的数据)
//直接改变原始数组
//放在数组末尾
//返回值 :添加数据后数组长度
var res= arr.push('hello','world')
console.log(arr) //(7) [1, 2, 3, 4, 5, "hello", "world"]
console.log(res) //7


//2.pop()删除数组中的最后一个数据
//语法:数据.pop()
//直接改变原始数组
//返回值:被删除的那一个数据
var res=arr.pop()
console.log(arr) //(6) [1, 2, 3, 4, 5, "hello"]
console.log(res) //world

//3.unshift()向数组中添加数据
//语法 数组.push(需要添加的数据)
//添加在数组前(第一个)
//直接改变原始数组
//返回值 :添加数据后数组长度
var res=arr.unshift('access')
console.log(arr) //(7) ["access", 1, 2, 3, 4, 5, "hello"]
console.log(res) //7

//plus()和 unshift() 区别 一个在后,一个在前 . 对内存水泵与时间复杂度不一样

//4.shift() 删除数组中的第 0 个数据 索引为0
//语法: shfit()
//直接改变原始数组
//返回值:被删除的那一个数据
var res =arr.shift()
console.log(arr) //(6) [1, 2, 3, 4, 5, "hello"]
console.log(res) //access

</script>

原文地址:https://www.cnblogs.com/d534/p/12710216.html