JS生成多维数组的通用方法

作者:frank 发表日期:2016-08-04 20:00:35 更新日期:2016-08-15 20:16:03 分类:猿文色

摘要

JS生成多维数组的通用方法

正文

代码(Code)

// DeepCopy of Array, all the element of array must be basic data types.
Array.prototype.deepCopy = function() {
    return this.map(function(ele) {
        if(Array.isArray(ele)) {
            return ele.deepCopy();
        } else {
            return ele;
        }
    });
};

var MultiArray = function() {
    if (!MultiArray.isArgsValidate && [].filter.call(arguments, function(arg) {
            return +arg !== parseInt(arg);
        }).length > 0) {
        console.log('All arguments must be int');
        return;
    }

    MultiArray.isArgsValidate = true;

    var length = arguments.length;
    var result = [];
    var temp = 0;

    if (length > 1) {
        temp = MultiArray.apply(null, [].slice.call(arguments, 1));
    } else {
        MultiArray.isArgsValidate = false;
    }

    for (var i = 0; i < arguments[0]; i++) {
        result[i] = temp === 0 ? temp : temp.deepCopy();
    }

    return result;
};

用法(Usage)

params are the array dimensions

new MultiArray(3, 3, 3); // generate a 3*3*3 multi-array
new MultiArray(2, 2); // generate a 2*2 multi-array

样例(Demo)

此处输入图片的描述