2014-05-24 4 views
2

내가 하나에 별도의 목록에서 추가 루프이이이 코드가 작동 $scope.statsindexOf()가 올바른 값에 -1을 반환하는 이유는 무엇입니까?

for (var i = 0; i < $scope.totalNames.length; i++) { 
    var list = $scope.totalNames[i]; 
    for (var j = 0; j < list.length; j++) { 
     var quote = list[j].quote; 
     if (typeof localStorage[quote] == "undefined") { 
      localStorage[quote] = 0; 
     } 
     $scope.stats.pushUnique({quote: quote, value: localStorage[quote]}); 
    } 
} 

을했다. 문제는 아래에 있으며 indexOf가 -1을 반환하고 {quote: quote, value: localStorage[quote]}은 목록의 요소와 정확히 동일한 값이지만 -1이 반환됩니다.

$scope.arrayObjectIndexOf = function(myArray, property, searchTerm){ 
    for(var i = 0, len = myArray.length; i < len; i++) { 
     if (myArray[i][property] === searchTerm) return i; 
    } 
    return -1; 
} 
+2

예상대로 작동하지 않는 객체 배열에 대해'indexOf'를 사용하려고합니다. 이것은 가능한 객체 배열 ** indexOf 메서드 ** (http://stackoverflow.com/questions/8668174/indexof-method-in-an-object-array)와 [** Javascript 배열 .indexOf는 개체를 검색하지 않습니다 **] (http://stackoverflow.com/questions/12604062/javascript-array-indexof-doesnt-search-objects) – Nope

+0

위대한,이 감사합니다! – benjipelletier

답변

-1

이 사용자 정의 기능은 내 문제를 해결 indexOf)하지만 원하는 것은 quote: quotevalue: localStorage[quote] 인 모든 객체의 indexOf를 찾는 것입니다. 인용 한 값 :

var found = $scope.stats.filter(function(stat){ return stat.quote == quote && stat.value == localStorage[quote]; }); 
var index = -1; 
if(found.length > 0) 
    index = $scope.stats.indexOf(found[0]); 

견적 일치 첫 번째 항목의 오브젝트 레퍼런스를 얻을 것이다 로컬 스토리지 [인용] 다음 배열의 해당 항목의 인덱스를 찾는.

+1

[지불 기한이 어디인지 알려주세요] (http://stackoverflow.com/a/8668283/453331). – kba

0

하면 객체, {quote: quote, value: localStorage[quote]}indexOf을 요청, 그냥 당신의 전화에서 만든 특정 객체에 대한 참조 (을 찾고 :

//below is stated in a function where the quote var has the same value as quote var above 

var index = $scope.stats.indexOf({quote: quote, value: localStorage[quote]}, 0); 

alert(index); //returns -1 
0

2 개의 개체가 동일하지 않기 때문입니다. 두 개체는 == 비교를 사용하여 비교할 수 없습니다.

정확히 동일한 내용을 가지고 있지만 두 객체 모두 JavaScript에 다른 객체 ID가 첨부되어 있기 때문입니다. 오브젝트가 다른 오브젝트를 참조하므로 .indexOf은 ID가 y 인 오브젝트만을 포함하는 배열에 x이라는 ID를 가진 오브젝트를 찾을 수 없습니다.

indexOf 그러나 인수와 완전히 동일한 개체를 제공 할 때는 indexOf을 사용하십시오. 예를 들어

var obj = {a:'b'}; 
[obj, 1, 2, 3].indexOf(obj); //returns 0 

그 때문에 실제로 그 배열의 존재 x의 ID를 갖는 객체를 찾고있다.

관련 문제