下划线 uniq 在 Parse 中不起作用
Underscore uniq not working in Parse
我有一个简单数组 cars
class Cars
的 Parse 模型
当我做
var uniqCars = _.uniq(cars);
没用。 uniqCars
与 cars
完全相同。 cars
的长度是5,uniqCars
的长度是5(应该是2)。
然而,当我这样做时:
var uniqCars = _.uniq(cars,
function (c) {
return c.id;
});
有效。我的问题是,为什么它不与前者一起工作而与后者一起工作?为什么我必须如此冗长?这是 Parse 或下划线的问题吗?
比较是使用严格相等进行的。除非对数组中的同一个对象有多个引用,否则它们不会严格相等。
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.
why doesn't it work with the former
因为,如果不传递比较器函数,它默认使用 ===
运算符来比较对象。引用 _.uniq
文档,
Produces a duplicate-free version of the array, using === to test object equality. ... If you want to compute unique items based on a transformation, pass an iteratee function
当您使用 ===
(Strict Equality operator) 时,没有两个对象是相同的,除非它们是同一个对象或构成字符串的相同字符序列。例如,
console.assert(({} === {}) === false);
var obj = {};
console.assert(obj === obj);
console.assert("ab" === "a" + "b")
console.assert("ab" === 'a' + "b")
因此,它不是特定于 Parse,但它是 JavaScript 中的预期行为。
我有一个简单数组 cars
class Cars
当我做
var uniqCars = _.uniq(cars);
没用。 uniqCars
与 cars
完全相同。 cars
的长度是5,uniqCars
的长度是5(应该是2)。
然而,当我这样做时:
var uniqCars = _.uniq(cars,
function (c) {
return c.id;
});
有效。我的问题是,为什么它不与前者一起工作而与后者一起工作?为什么我必须如此冗长?这是 Parse 或下划线的问题吗?
比较是使用严格相等进行的。除非对数组中的同一个对象有多个引用,否则它们不会严格相等。
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.
why doesn't it work with the former
因为,如果不传递比较器函数,它默认使用 ===
运算符来比较对象。引用 _.uniq
文档,
Produces a duplicate-free version of the array, using === to test object equality. ... If you want to compute unique items based on a transformation, pass an iteratee function
当您使用 ===
(Strict Equality operator) 时,没有两个对象是相同的,除非它们是同一个对象或构成字符串的相同字符序列。例如,
console.assert(({} === {}) === false);
var obj = {};
console.assert(obj === obj);
console.assert("ab" === "a" + "b")
console.assert("ab" === 'a' + "b")
因此,它不是特定于 Parse,但它是 JavaScript 中的预期行为。