(新的Array(x)).map的奇怪之处 [英] (new Array(x)).map stranges

查看:87
本文介绍了(新的Array(x)).map的奇怪之处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了奇怪的行为(已在Chrome上进行了测试)

I found strange behavior ( tested at Chrome )

[1,2].map(function() { console.log(arguments); })
// [1, 0, Array[2]]
// [2, 1, Array[2]]
// [undefined, undefined]

没关系-就像文档中的一样 但是

and that's ok -- ok as in documentation But

(new Array(20)).map(function() { console.log(arguments); })
//[undefined × 20]

它不使用回调(没有动作,内部的debugger不起作用,等等.).为什么?

It doesn't use callback ( no actions, debugger inside doesn't work etc. ). Why??

语法new Array(arrayLength)应该创建具有给定长度的数组.确实如此.但是.map怎么办?

Syntax new Array(arrayLength) should create array with given length. And it does. But what with .map?

推荐答案

来自

回调仅对已分配的数组索引进行调用 值,包括未定义.它不要求缺少的元素 数组(即从未设置的索引,已设置的索引 删除或从未分配过值).

callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

使用new Array()声明数组时,所有元素均未定义,但尚未作为 value 进行赋值 undefined.因此,在呼叫map()时会跳过它们.

When you declare an array using new Array(), all of the elements are undefined, but they have not been assigned undefined as a value. Therefore, they are skipped in the call to map().

您可以使用join()split()显式地将undefined分配给每个元素,然后将获得预期的输出:

You can use join() and split() to explicitly assign undefined to each element, and you'll then get the expected output:

(new Array(20).join(undefined).split(undefined)).map(function() { console.log(arguments); })

这篇关于(新的Array(x)).map的奇怪之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆