- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
有没有规范化数组返回值和变异的 JavaScript 数组库?我认为 JavaScript Array 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
有些只是返回undefined:
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();
这对大多数变异方法都适用,但也存在问题。例如,我需要为每个不改变原始数组的方法编写自定义原型(prototype)。
所以在我做这件事的时候,我一直在想,也许以前有人做过这件事?是否已经有任何轻量级数组库可以做到这一点?如果该库还为旧浏览器的新 JavaScript 1.6 方法添加垫片,那就太好了。
最佳答案
我不认为它真的不一致。是的,它们可能有点令人困惑,因为 JavaScript 数组完成了其他语言具有单独结构(列表、队列、堆栈等)的所有事情,但它们的定义在不同语言中是非常一致的。您可以轻松地将它们分组到您已经描述的那些类别中:
push
/unshift
返回添加元素后的长度pop
/shift
返回请求的元素splice
是用于在列表中间删除/替换/插入项目的多用途工具 - 它返回已删除元素的数组。sort
和 reverse
是两种标准的就地重新排序方法。所有其他方法都不会修改原始数组:
slice
按位置获取子数组,filter
按条件获取子数组,concat
与其他数组组合创建并返回新数组<forEach
只是迭代数组,不返回任何内容every
/some
测试项目的条件,indexOf
和 lastIndexOf
搜索项目(通过相等) - 都返回结果reduce
/reduceRight
将数组项缩减为单个值并返回该值。特殊情况是:
map
缩减为一个新数组 - 它类似于 forEach
但返回结果join
and toString
reduce to a string这些方法足以满足我们的大部分需求。我们可以用它们做任何事情,而且我不知道有任何库向它们添加类似但在内部或结果方面不同的方法。大多数数据处理库(如 Underscore)仅使它们跨浏览器安全(es5-shim)并提供额外的实用方法。
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.
我想说 JavaScript 的一致性是在修改元素或长度时总是返回一个新数组。我猜这是因为对象是引用值,更改它们经常会在引用同一数组的其他作用域中引起副作用。
链接仍然是可能的,你可以使用 slice
, concat
, sort
, reverse
, filter
和 map
只需一步即可创建一个新数组。如果只想“修改”数组,只需将其重新分配给数组变量即可:
A = A.slice(0,1).reverse().concat(['a','b']);
变异方法对我来说只有一个优势:它们更快,因为它们可能更节省内存(当然,取决于实现及其垃圾收集)。因此,让我们为这些实现一些方法。作为Array subclassing既不可能也没有用,我将在 native prototype 上定义它们:
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');
关于javascript - 规范化数组方法和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13136688/
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!