一,sessionStorage、localStorage和cookie的区别
共同点:都是保存在浏览器端、且同源的
区别:
1、cookie数据始终在同源的http请求中携带(即使不需要),即cookie在浏览器和服务器间来回传递,而sessionStorage和localStorage不会自动把数据发送给服务器,仅在本地保存。cookie数据还有路径(path)的概念,可以限制cookie只属于某个路径下
2、存储大小限制也不同,cookie数据不能超过4K,同时因为每次http请求都会携带cookie、所以cookie只适合保存很小的数据,如会话标识。sessionStorage和localStorage虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大
3、数据有效期不同,sessionStorage:仅在当前浏览器窗口关闭之前有效;localStorage:始终有效,窗口或浏览器关闭也一直保存,因此用作持久数据;cookie:只在设置的cookie过期时间之前有效,即使窗口关闭或浏览器关闭
4、作用域不同,sessionStorage不在不同的浏览器窗口中共享,即使是同一个页面;localstorage在所有同源窗口中都是共享的;cookie也是在所有同源窗口中都是共享的
5、web Storage支持事件通知机制,可以将数据更新的通知发送给监听者
6、web Storage的api接口使用更方便
二,伪数组
假如有这样一段代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul id = 'ul'>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script>
var liArr = document.getElementById('ul')
console.dir(liArr.children)
</script>
</html>

上图就是一个伪数组,长相很像数组,但是将他的原型proto打开看看,它没有数组的splice,concat,pop等方法

将伪数组转化为真数组
Array.prototype.slice.call(liArr.children)

原理
借用数组原型方法:
var arr = Array.prototype.slice.call(liArr.children);
Array.prototype.forEach.call(liArr.children, function(v) {
// 循环liArr.children对象
});
可以简化为:
Array.prototype.slice.call(liArr.children)
总结
伪数组没有数组 Array.prototype 的属性值,类型是 Object ,而数组类型是 Array
数组是基于索引的实现, length 会自动更新,而对象是键值对
使用对象可以创建伪数组,伪数组可以利用call或者apply很方便的转化为真数组
网友评论