Compare JavaScript values of different type (not strings)?
How can I find all items in an array by matching a property and dealing with case insensitivity ONLY IF the values are strings? I have no way to know what data type the property on the object will be. Both the target value and property may be a date, string, number, etc.
I'm basically trying to protect the next developer from shooting himself in the foot:
function getItemsByKey(key, value, isCaseSensitive) {
var result = [];
(getAll() || []).forEach(function(item){
if (!(!!isCaseSensitive)) {
if (item[key] && item[key].toString().toLowerCase() == value.toString().toLowerCase()) { result.push(item); }
} else {
if (item[key] == value) { result.push(item); }
}
});
return result;
}
What happens if they pass in isCaseSensitive = true
and the values end up being dates or numbers... or mismatched?
请参阅行内评论。
function getItemsByKey(key, value, isCaseSensitive) {
var result = [];
(getAll() || []).forEach(function(item){
// Either the values are equal OR (not case sensitive AND item[key] and value are strings AND non-case sensitive match)
if (item[key] == value || (
!isCaseSensitive &&
typeof item[key] == 'string' &&
typeof value == 'string' &&
item[key].toLowerCase() == value.toLowerCase())
) {
result.push(item);
}
});
return result;
}
链接地址: http://www.djcxy.com/p/94998.html