Currently I am doing the following to check if a String
exists in an array:
$('#finance').click(function(){ // Show Finance & OD
console.log('Finance jobs');
for(i = 0; i < jobs.length; i ++){
if(jobs[i].department === "Finance & OD"){
console.log(jobs[i]);
}
}
});
However, I'd like to just check if a sub string
exists and for it to not be case sensitive. So I tried this but It did not work:
$('#finance').click(function(){ // Show Finance & OD
console.log('Finance jobs');
for(i = 0; i < jobs.length; i ++){
if(jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
console.log(jobs[i]);
}
}
});
I got this error in the console window: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
I'm wondering how I could fix my code so that rather checking for the entire string, I would check for part of the String say "Finance" for example and that it would not be case sensitive.
Do it like this:
$('#finance').click(function(){ // Show Finance & OD
console.log('Finance jobs');
for(i = 0; i < jobs.length; i ++){
if(jobs[i].department != 'undefined' && jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
console.log(jobs[i]);
}
}
});
I think the problem is that you loop through some "undefineds" and therefor get an uncatched exception.
This is you can check for particular word and also not case-sensitive:
var jobs = ["Finance & OD", "texT"];
for( var i in jobs ) {
var regex = new RegExp( "Finance", "i" );
if( jobs[i].match( regex ) ) {
console.log(jobs[i]);
}
}
You need to check for undefined. Try this:
if(jobs[i].department != "undefined" && jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
console.log(jobs[i]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.