我想在我的代碼中使用lodash的_.includes
方法,但任何時候我有一個對象數組我不能得到它的工作,而是最終依靠_.find
方法。需要幫助的理解lodash的_.includes方法
從我的測試中我只能得到_.includes
與簡單的數組一起工作。但也許這就是它應該工作的方式?
我對Lodash和一般編程非常新,所以我想我會問,如果我缺少一些關於如何使用此方法的信息。
我創建了一個jsbin用下面的代碼:http://jsbin.com/regojupiro/2/
var myArray = [];
function createArray(attName, attId, otherId) {
var theObject = {};
theObject.attributeName = attName;
theObject.attributeId = attId;
theObject.otherId = [otherId];
return theObject;
}
myArray.push(createArray('first', 1001, 301));
myArray.push(createArray('second', 1002, 302));
myArray.push(createArray('third', 1003, 303));
myArray.push(createArray('fourth', 1004, 304));
var isPresent1 = _.includes(myArray, {'attribtueId' : 1001});
var isPresent2 = _.includes(myArray, 1001);
var found = _.find(myArray, {'attributeId' : 1001});
console.log(isPresent1);
console.log(isPresent2);
console.log(found);
console.log(myArray);
兩個 「isPresent」 變量返回false,但_.find
方法返回正確的對象。
如果我只需要做一個簡單的真/假檢查來查看一個值是否存在於我的對象數組中,我會更好地理解如何使用_.includes
方法。
或者,如果這是該作業的錯誤工具,_.find
方法是這個工作的正確工具,還是我還不熟悉的其他一些lodash方法?
謝謝你的幫助!
好的,這對我來說更有意義。我很驚訝沒有一種方法可以爲一組對象返回true/false。謝謝你的幫助! – Zigrivers 2015-03-31 19:07:01
你知道這是每個機會的時間複雜性嗎? – fungusanthrax 2017-05-09 21:09:15
@fungusanthrax什麼*時間複雜性是什麼?像'_.includes()'是線性的(* O(n)*)。 – Pointy 2017-05-09 23:48:00