问题
$(document).ready(function(){
var textsearch = "XYZ"
$.ajax({
dataType: 'jsonp', //data in jsonp
contentType: "application/json; charset=utf-8",
url: 'http://live.nhle.com/GameData/RegularSeasonScoreboardv3.jsonp',
jsonpCallback: 'loadScoreboard',
success: function (data) {
console.log(data);
if(textsearch)
{
for (var key in data)
{
if(data[key].hasOwnProperty('htn') && data[key].hasOwnProperty('atn'))
{
if((data[key]['htn'].toLowerCase()).indexOf(datasearch.toLowerCase()) != -1 || (data[key]['atn'].toLowerCase()).indexOf(textsearch.toLowerCase())!=-1)
times ++;
}
}
}
alert("Found " + textsearch + " " + times + " times");
---- How do I rewrite the search function (from if (text search) down) in order to have it loop through data.games and also have it record the score as well.
http://jsfiddle.net/draditya91/548Az/1/
回答1:
Here is the Updated Fiddle
Just search for the word and fetch scores if there is a match and display
for (var key in text)
{
if(text[key].hasOwnProperty('htn') && text[key].hasOwnProperty('hts'))
{
if(text[key]['htn'].toLowerCase().indexOf(textsearch.toLowerCase()) != -1)
str= text[key]['htn']+ " vs "+ text[key]['atn']+ " score : "+ text[key]['hts']+"-"+text[key]['ats']+"\n";
if( text[key]['atn'].toLowerCase().indexOf(textsearch.toLowerCase())!=-1)
str += text[key]['atn'] + " vs "+ text[key]['htn']+ " score : "+ text[key]['ats']+"-"+text[key]['hts'];
}
}
alert(str);
回答2:
if data.games is an array you could do
data.games.map(function(e){return e.score});
and you will get an array of scores. If you want all of the scores added up you could do...
data.games
.map(function(e){return e.score})
.reduce(function(prev,current){return prev+current});
If you want the teams and the score
data.games.map(function(game){
return{
team1: game.team1Name,
team2: game.team2Name,
score: game.score
}
});
That will give you an array of objects with the attributes of both team names and the score
来源:https://stackoverflow.com/questions/22842339/how-do-i-rewrite-the-search-function-by-adding-a-for-loop-to-go-through-data-gam