2013-06-13 71 views
1

這裏是一個小例子裏面:如何尋找一個String對象的數組(結構)

var distinctValues = []; 
distinctValues.push("Value1"); 
distinctValues.push("Value2"); 

var firstValue = distinctValues[0]; 

var searchResults = []; 

var data = grid.jqGrid('getGridParam', 'data'); 
data.forEach(function (row) { 

    searchResults[searchResults.length] = 
    { 
    "ID"  : row.ID, 
    "CreatedBy": row.CreatedBy, 
    "UpdatedBy": row.UpdatedBy 
    } 
} 

我看上去怎麼樣firstValue(「值1」)SearchResult所陣列並檢索CreatedBy信息?

//something like this - this is wrong syntax by the way 
if ($.inArray(firstValue, searchResults) != -1) { 
     alert(searchResults["CreatedBy"]); 
} 

回答

1

我想你可能要做到這一點:

var searchResults = []; 
data.forEach(function (row) { 

    searchResults.push({ //Push to push the record to the array 
    "ID"  : row.ID, 
    "CreatedBy": row.CreatedBy, 
    "UpdatedBy": row.UpdatedBy 
    }); 
} 

您可以使用jQuery $ .inArray或Array.prototype.indexOf

SearchResult所爲對象的數組,所以使用索引即​​代替searchResults["CreatedBy"]

var idx = searchResults.indexOf(firstValue); //or var idx = $.inArray(firstValue, searchResults) 
if (idx > -1) { 
     alert(searchResults[idx]["CreatedBy"]); //item Found 
} 

y沒有問題我們的語法爲$.inArray,前提是您的代碼中包含jquery。

因爲你的對手是針對一個對象的屬性,你可以試試這個:

var result = $.grep(searchResults, function(value) 
    { 
     return value.ID === firstValue; 
    }); 

    console.log(result[0].CreatedBy); //result will be an array of matches. 
+0

我們可以使用'ARR [arr.length]'添加元素..但'arr.push'更最快 – rab

+0

@ rab猜猜OP的問題是與索引器... – PSL

+0

不幸的是,總是返回-1。我調試它,並可以看到該值存在於數組中:-( – Max