Array构造函数的合法使用

Šim*_*das 13 javascript arrays constructor

我喜欢这个问题 - 函数构造函数的合法使用 - 所以我想创建一个关于Array构造函数的类似问题.

当然,数组文字表示法是创建数组的正确方法.这意味着new Array不应使用符号.并且"案件结案".

但是,new Array表格有一个特殊性.如果传入自然数,则会创建一个空数组,并将其length属性设置为该数字.

所以

arr = new Array( 7 );
Run Code Online (Sandbox Code Playgroud)

相当于

arr = [];
arr.length = 7;
Run Code Online (Sandbox Code Playgroud)

这可以被视为一项功能.我想知道这个"功能"是否具有实际用途.我最近偶然发现了一个这样的(简单)用法:

new Array( n + 1 ).join( '*' ) // returns string containing n stars

// e.g.
new Array( 3 ).join( '*' ) // returns '**'
new Array( 6 ).join( '*' ) // returns '*****'
Run Code Online (Sandbox Code Playgroud)

这很酷,但希望有一些更高级的用途.(可以使new Array符号成为JavaScript程序中合法工具的东西.)


更新:我注意到jQuery库new Array( len )在一个实例中使用了表示法 - 它在when函数内部(搜索"when:"):

when: function( firstParam ) {
    var args = sliceDeferred.call( arguments, 0 ),
        i = 0,
        length = args.length,
        pValues = new Array( length ),
        count = length,
        pCount = length,
        // etc.
Run Code Online (Sandbox Code Playgroud)

他们使用它来初始化pValues局部变量,该变量在代码中的下一个本地函数中使用:

function progressFunc( i ) {
    return function( value ) {
        pValues[ i ] = arguments.length > 1 ?
                sliceDeferred.call( arguments, 0 ) : value;
        deferred.notifyWith( promise, pValues );
    };
}
Run Code Online (Sandbox Code Playgroud)

我很想知道是否将作业改为公正

pValues = [],
Run Code Online (Sandbox Code Playgroud)

会破坏程序......(正常工作new Array( length )需要notifyWith吗?)

Rig*_*red 3

作为浅克隆数组的替代方法怎么样?

var arr = [1,2,3];

var arr2 = Array.apply( null, arr );

arr === arr2; // false;

arr.length === arr2.length; // true
Run Code Online (Sandbox Code Playgroud)

是的,我到达这里是因为您只是使用.slice(),但我真的不认为使用首先Array是非法的,只要您知道自己在做什么。


偏离主题,但使用Arrayor来创建通用函数的一种方法slice。需要bind. 现在太懒了,无法更新旧版浏览器。

http://jsfiddle.net/fdgBU/1/

var slicer,
    apply = Function.prototype.apply;

if( apply.bind ) {
    try {
        (slicer = apply.bind( Array, null ))({length:0});
    } catch( e ) {
        slicer = apply.bind([].slice);
    }
} else {
   slicer = function( coll ) {
        if( !coll || coll.length !== +coll.length ) return;
        var res = [], i = 0, len = coll.length >>> 0;
        for( ; i < len; ++i ) {
            res[i] = coll[i];
        }
        return res;
    };
}
Run Code Online (Sandbox Code Playgroud)
var arr_like = {'0':true,'1':true,'2':true,length:3},
    arr = slicer( arr_like );

console.log( arr ); // [true, true, true]

console.log( arr.length === arr_like.length); // true
Run Code Online (Sandbox Code Playgroud)

  • @Pointy:悬念快要了我的命! (4认同)
  • 噢,抱歉@RightSaidFred - 我被打扰了。不管怎样,问题是,当你使用服务器端模板语言(php、jsp,等等)时,你编写一个“new Array(${foo})”,其中“foo”*通常*是一个数字列表,但有时它只是一个数字,那么事情就不会那么顺利了:-)我只是喜欢养成使用括号表示法的习惯;反正打字也少了。 (2认同)