js 向数组头部、或尾部添加元素,在此记录一下
1、js 向数组头部添加元素
使用 unshift 方法
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var citys = [
{id:'2', name: '卢俊义'},
{id:'3', name: '吴用'}
]
console.log('unshift前')
console.log(JSON.stringify(citys))
citys.unshift({id:'1', name: '宋江'});
console.log('unshift后')
console.log(JSON.stringify(citys))
</script>
</body>
</html>
运行效果
2、js 向数组尾部添加元素
使用 push 方法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var citys = [
{id:'1', name: '宋江'},
{id:'2', name: '卢俊义'}
]
console.log('push前')
console.log(JSON.stringify(citys))
citys.push({id:'3', name: '吴用'});
console.log('push后')
console.log(JSON.stringify(citys))
</script>
</body>
</html>
运行效果
至此完