下划线:使用集合方法包装数组

bod*_*ser 1 javascript underscore.js

我有一个充满对象的数组:

var myArray = [{ "user": "anton" }, { "user": "joe" }];
Run Code Online (Sandbox Code Playgroud)

我现在想把数组包装成一个Underscore Collection对象,这样我就可以使用下划线的集合方法(删除,添加):

myArray = _(myArray); // this only add object methods
myArray.add({ "user": "paul" });
Run Code Online (Sandbox Code Playgroud)

那么如何用下划线包装数组以使用下划线集合方法

ggo*_*zad 7

为了记录,因为接受的答案是误导性的:

Underscore用作函数,包装其参数,即

_([a, b, c])
Run Code Online (Sandbox Code Playgroud)

相当于:

_.chain([a, b, c])
Run Code Online (Sandbox Code Playgroud)

实际上chain定义为:

_.chain = function(obj) {
  return _(obj).chain();
};
Run Code Online (Sandbox Code Playgroud)

现在问你的问题:

你混淆Bac​​kbone提供集合,而Underscore则没有.可以从阵列轻松初始化骨干集合,例如:

var c = new Backbone.Collection([{ "user": "anton" }, { "user": "joe" }]);
Run Code Online (Sandbox Code Playgroud)

会工作得很好.你还可以做:

c.add({ "user": "paul" });
Run Code Online (Sandbox Code Playgroud)

  • `_([a,b,c])`不等于`_.chain([a,b,c])` (2认同)