将构造函数传递给Array.map? [英] Passing a constructor to Array.map?

查看:111
本文介绍了将构造函数传递给Array.map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做:

var a = [1,2,3,4];
a.map(Date.constructor);

此代码在Google V8上引发错误:

This code throws an Error on Google V8:

SyntaxError: Unexpected number

我也尝试过:

a.map(Date.constructor, Date.prototype)

具有相同的结果。

推荐答案

Date是一个函数,因此Date.constructor是函数的构造函数。
正确调用Date对象构造函数如下所示:

The Date is a function, so the Date.constructor is a constructor of a function. Proper call of the Date object constructor looks like this:

Date.prototype.constructor();

或者只是:

Date();

这里的问题是创建一个Date对象数组,其时间值来自数组 a
无法调用Date对象构造函数并在没有 new 运算符的情况下向其传递参数(ECMA-262 15.9.2)

The problem here is to create an array of Date objects with time values from array a, but it is impossible to call the Date object constructor and pass an arguments to it without a new operator (ECMA-262 15.9.2).

但任何可以作为函数调用的对象构造函数都可能具有与i相同的结果使用 new 运算符(例如Error对象构造函数(ECMA-262 15.11.1))。

But it is possible for any object constructors that can be called as a functions with the same result as if i use the new operator (for instance the Error object constructor (ECMA-262 15.11.1)).

$ var a = ['foo','bar','baz'];
$ a.map(Error);
> [ { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'foo' },
    { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'bar' },
    { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'baz' } ]

这篇关于将构造函数传递给Array.map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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