Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第55题(2019-10-11):在Javascript中什么是伪数组?如何将伪数组转化为标准数组? #57

Open
qappleh opened this issue Oct 11, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 11, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Oct 12, 2019

伪数组(类数组):无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以对真正数组遍历方法来遍历它们。典型的是函数的argument参数,还有像调用getElementsByTagName,document.childNodes之类的,它们都返回NodeList对象都属于伪数组。可以使用Array.prototype.slice.call(fakeArray)将数组转化为真正的Array对象。

假设我们定义一个log方法,要给每个log方法添加一个"(app)"前缀,比如'hello world!' ->'(app)hello world!'。方法如下:


function log(){
  var args = Array.prototype.slice.call(arguments);  //为了使用unshift数组方法,将argument转化为真正的数组
  args.unshift('(app)');
  console.log.apply(console, args);
};  

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant