规范化Array方法和返回值 [英] Normalize Array methods and return values

查看:183
本文介绍了规范化Array方法和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有标准化的数组返回值和突变任何JavaScript库阵?我认为JavaScript的数组API很不一致。

Is there any JavaScript Array library that normalizes the Array return values and mutations? I think the JavaScript Array API is very inconsistent.

一些方法变异数组:

var A = [0,1,2];
A.splice(0,1); // reduces A and returns a new array containing the deleted elements

有些则没有

A.slice(0,1); // leaves A untouched and returns a new array

有的返回突变数组的引用:

Some return a reference to the mutated array:

A = A.reverse().reverse(); // reverses and then reverses back

有的只是返回未定义的:

Some just return undefined:

B = A.forEach(function(){});

我想是要始终变异阵列和永远返回相同的阵列,这样我就可以有某种一致性,也能链。例如:

What I would like is to always mutate the array and always return the same array, so I can have some kind of consistency and also be able to chain. For example:

A.slice(0,1).reverse().forEach(function(){}).concat(['a','b']);

我尝试了一些简单的代码片段,如:

I tried some simple snippets like:

var superArray = function() {
    this.length = 0;
}

superArray.prototype = {
    constructor: superArray,

    // custom mass-push method
    add: function(arr) {
        return this.push.apply(this, arr);
    }
}

// native mutations
'join pop push reverse shift sort splice unshift map forEach'.split(' ').forEach(function(name) {
    superArray.prototype[name] = (function(name) {
        return function() {
            Array.prototype[name].apply(this, arguments);
            // always return this for chaining
            return this;
        };
    }(name));
});

// try it
var a = new superArray();
a.push(3).push(4).reverse();

这适用于大多数基因突变的方法,但也存在问题。比如我需要编写自定义的原型各不变异原数组方法。

This works fine for most mutation methods, but there are problems. For example I need to write custom prototypes for each method that does not mutate the original array.

所以,一如既往我这样做的同时,我在想,也许这之前已经做了什么?有没有已经这样做了的轻量级阵列库?这将是很好,如果库还增加了新的JavaScript 1.6垫片的方法对旧版浏览器。

So as always while I was doing this, I was thinking that maybe this has been done before? Are there any lightweight array libraries that do this already? It would be nice if the library also adds shims for new JavaScript 1.6 methods for older browsers.

推荐答案

我不认为这真的是不一致的。是的,他们可能会有点混乱,如JavaScript数组做所有这些其他语言有不同的结构(列表,队列,栈,...),但他们的定义是不同的语言相当一致的东西。您可以轻松地将它们分组在你已经描述的那些类:

I don't think it is really inconsistent. Yes, they might be a little confusing as JavaScript arrays do all the things for which other languages have separate structures (list, queue, stack, …), but their definition is quite consistent across languages. You can easily group them in those categories you already described:

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