开发者社区 问答 正文

在 Javascript 中什么是伪数组?如何将伪数组转化为标准数组?

在 Javascript 中什么是伪数组?如何将伪数组转化为标准数组?

展开
收起
kun坤 2019-11-28 14:17:36 529 分享 版权
1 条回答
写回答
取消 提交回答
  • 答案:

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

    假设我们要给每个 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);
    }
    
    2019-11-28 14:17:47
    赞同 展开评论
问答分类:
问答标签:
问答地址: