array of objects vs array of delimited array of strings
I need to create an array of searchable items but I'm not sure whether I should create an array of custom objects or just an array of delimited strings. Can someone give me some advice on which is the better way. Below is an example:
var Arr = [ "Arts Tower|ArtsTower.htm|104",
"Arts Tower|ArtsTower.htm|1203",
"Arts Tower|ArtsTower.htm|Arts Tower"
];
var searchTerm = "tow"
var ArrResults = jQuery.grep(Arr, function(value, index){
return (value.split("|")[2].toLowerCase().indexOf(searchTerm) != -1);
});
or
function Item(name, url, str){
this.name = name;
this.url = url;
this.str= str;
}
var Arr = new Array();
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "104"));
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "1203"));
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "Arts Tower"));
var searchTerm = "tow"
var ArrResults = jQuery.grep(Arr, function(value, index){
return 开发者_运维问答(value.str.toLowerCase().indexOf(searchTerm) != -1);
});
I need to search the array and return back any matches. Which would perform better?
Using Array and Object constructors and pushing items to an array is an overkill (and unnecessary for static data like yours).
Using proprietary encoding (using pipe delimiters) that needs additional processing to parse is also not favorable.
I would go with an array of objects in literal form:
var Arr = [
{ name: "Arts Tower", url: "ArtsTower.htm", str: "104" },
{ name: "Arts Tower", url: "ArtsTower.htm", str: "1203" },
{ name: "Arts Tower", url: "ArtsTower.htm", str: "Arts Tower" }
];
This also brings you closer to a point where you would want to load the data via XHR ($.ajax).
I don't know which one of your suggestions are faster, but I would personally use the second example. This is because of later usage of your ArrResults arary. If that array contains strings, you would have to split it every time you'd use one of your results, like this: ArrResults[0].split('|')[0]
instead of just ArrResults[0].name
精彩评论