惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
V
Visual Studio Blog
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
L
LangChain Blog
Martin Fowler
Martin Fowler
GbyAI
GbyAI
博客园 - 司徒正美

博客园 - Q.Lee.lulu

aProxy: 带认证授权和权限控制的反向代理 Nginx做前端Proxy时TIME_WAIT过多的问题 Cubieboard通过aria2和minidlna来架设家庭媒体中心 与IT&码农有关的电影和记录片 golang与node.js的http模块性能对比测试(go1) 用OpenCv来做人脸识别 linux下SublimeText的中文输入法问题之解决方案 golang与node.js的http对比测试 作为Web开发人员,我为什么喜欢Google Chrome浏览器 sqlalchemy在web.py中的session使用 web.py大文件下载 Python和Node.js支持尾递归吗? 小文件、nginx、Redis、Moosefs 一道JavaScript面试题(setTimeout) 用Eclipse调试Node.js代码 Javascript正则分组命名 抛弃Fastcgi,用uwsgi来部署你的Django程序吧 Node.js:用JavaScript写服务器端程序-介绍并写个MVC框架 FaWave(发微)-Chrome上的多微博全能插件
Javascript中的类数组对象
Q.Lee.lulu · 2011-05-05 · via 博客园 - Q.Lee.lulu

看到一句Javascript的代码:

function test(){
    var args = Array.prototype.slice.call(arguments);
}

第一感觉是这句代码不是多余么?这切分后不是返回一样的数组么?

不过又感觉没人这么蛋疼做这么无聊的事情吧,于是Google,于是发现,我错了!

因为arguments不是一个数组对象,虽然它有length属性,并且你在firebug或者Chrome的控制台log出来的结果和数组一样。

function testArguments(){
    console.log(arguments);  
    console.log(arguments.length);
    console.log(arguments.constructor);
    console.log([].constructor);
    console.log('arguments.slice: ' + arguments.slice);
}

执行结果:

image

看到了吧~~ arguments并不是真正的数组对象。

function test(){
    var args = Array.prototype.slice.call(arguments);
}

所以,这里的Array.prototype.slice.call(arguments);其实是将arguments转换为真正的数组对象的。

参见:http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript

啊门!