Returning objects in Javascript
I have the following variable:
var tags = [{name:'Bold', key:'b'}, { name: 'Italic', key:'i'}]
Then, in order to get the correct tag I am working on I built a function:
function getCurrentTag(tagType) {
$.each(tags, function() {
if (tagType==this.name) {
return this;
}
});
}
开发者_运维百科And in the main scope I call it:
currentTag = getCurrentTag('Bold');
But currentTag is always "undefined".
How can I fix this?
Gidi
function getCurrentTag(tagType) {
for(var i = 0, len = tags.length; i < len; i++) {
if( tags[i].name === tagType )
return tags[i];
}
}
using jQuerys .each()
or for..in
loops to loop over an array is unecessary (slow).
Since $.each()
applies a callback function per interation you are returning that value to this anonymous function. You never return from getCurrentTag()
You never return the result of $.each()
.
Use a native javascript function. No need to use jQuery here.
var tags = [{name:'Bold', key:'b'}, { name: 'Italic', key:'i'}],
getCurrentTag = function (tags, name) {
var i = 0;
for (i = 0; i < tags.length; += 1) {
if (tags[i].name === name) {
return tags[i];
}
}
return False;
}
getCurrentTag(tags, 'Bold');
Why use an array? It would be so much cleaner with a simple object of name value pairs.
var tags = {'Bold':'b','Italic':'i'};
function getCurrentTag(tagType) {
return tags[tagType] || null;
}
All of that looping with your way of doing it will be slow:
精彩评论