Normalize Array方法和返回值



是否有任何JavaScript数组库可以规范化数组返回值和突变?我认为JavaScript数组API非常不一致。

一些方法变异数组:

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

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

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

有些只是返回未定义:

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

我想要的是总是对数组进行变异,并总是返回相同的数组,这样我就可以有某种一致性,也可以进行连锁。例如:

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

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

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();

这适用于大多数突变方法,但也存在一些问题。例如,我需要为每个不改变原始数组的方法编写自定义原型。

所以和往常一样,当我做这件事的时候,我在想,也许这件事以前也做过?有没有轻量级数组库已经做到了这一点?如果该库还为旧浏览器的新JavaScript1.6方法添加垫片,那就太好了。

我不认为它真的不一致。是的,它们可能有点令人困惑,因为JavaScript数组完成了其他语言具有单独结构(列表、队列、堆栈…)的所有任务,但它们的定义在不同语言之间是一致的。你可以很容易地将它们分组到你已经描述过的类别中:

  • 列出方法:
    • push/unshift返回添加元素后的长度
    • pop/shift返回请求的元素
    • 您可以定义用于获取第一个和最后一个元素的其他方法,但很少需要它们
  • splice是用于移除/替换/插入列表中间项目的通用工具,它返回已移除元素的数组
  • CCD_ 6和CCD_ 7是两种标准的就地重新排序方法

所有其他方法都不会修改原始数组:

  • slice按位置获取子数组,filter按条件获取子数组和concat与其他数组组合创建并返回新数组
  • forEach只是迭代数组,不返回任何结果
  • every/some测试项目的条件,indexOflastIndexOf搜索项目(相等)-均返回结果
  • reduce/reduceRight将数组项缩减为单个值并返回该值。特殊情况包括:
    • map缩减为一个新数组-它与forEach类似,但返回结果
    • CCD_ 20和CCD_

这些方法足以满足我们的大部分需求。我们可以用它们做任何事情,我不知道有任何库会为它们添加类似但内部或结果不同的方法。大多数数据处理库(如Undercore)只使它们跨浏览器安全(es5填充程序),并提供额外的实用程序方法。

我想要的是始终对数组进行变异,并始终返回相同的数组,这样我就可以具有某种一致性,也可以进行链式操作。

我认为JavaScript的一致性是在修改元素或长度时总是返回一个新数组。我想这是因为对象是引用值,更改它们通常会在引用同一数组的其他作用域中产生副作用。

使用sliceconcatsortreversefiltermap仍然可以进行链接,只需一步即可创建新阵列。如果您只想"修改"数组,您可以将其重新分配给数组变量:

A = A.slice(0,1).reverse().concat(['a','b']);

突变方法对我来说只有一个优点:它们更快,因为它们可能更节省内存(当然,这取决于实现及其垃圾收集)。因此,让我们实现一些方法。由于数组子类化既不可能也不有用,我将在原生原型上定义它们:

var ap = Array.prototype;
// the simple ones:
ap.each = function(){ ap.forEach.apply(this, arguments); return this; };
ap.prepend = function() { ap.unshift.apply(this, arguments); return this; };
ap.append = function() { ap.push.apply(this, arguments; return this; };
ap.reversed = function() { return ap.reverse.call(ap.slice.call(this)); };
ap.sorted = function() { return ap.sort.apply(ap.slice.call(this), arguments); };
// more complex:
ap.shorten = function(start, end) { // in-place slice
if (Object(this) !== this) throw new TypeError();
var len = this.length >>> 0;
start = start >>> 0; // actually should do isFinite, then floor towards 0
end = typeof end === 'undefined' ? len : end >>> 0; // again
start = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
ap.splice.call(this, end, len);
ap.splice.call(this, 0, start);
return this;
};
ap.restrict = function(fun) { // in-place filter
// while applying fun the array stays unmodified
var res = ap.filter.apply(this, arguments);
res.unshift(0, this.length >>> 0);
ap.splice.apply(this, res);
return this;
};
ap.transform = function(fun) { // in-place map
if (Object(this) !== this || typeof fun !== 'function') throw new TypeError();
var len = this.length >>> 0,
thisArg = arguments[1];
for (var i=0; i<len; i++)
if (i in this)
this[i] = fun.call(thisArg, this[i], i, this)
return this;
};
// possibly more

现在你可以做

A.shorten(0, 1).reverse().append('a', 'b');

IMHO最好的库之一是underscorejshttp://underscorejs.org/

您可能不应该仅为此使用库(添加到项目中不是很有用的依赖项)。

"标准"方法是在您想要执行变异操作时调用slice。这样做没有问题,因为JS引擎非常适合使用临时变量(因为这是javascript的关键点之一)。

示例:

function reverseStringify( array ) {
return array.slice( )
.reverse( )
.join( ' ' ); }
console.log( [ 'hello', 'world' ] );

最新更新