[英]Use JQuery to check if a String exists in an index of an Array
Currently I am doing the following to check if a String
exists in an array: 当前,我正在执行以下操作以检查数组中是否存在String
:
$('#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. 但是,我只想检查sub string
存在并且不区分大小写。 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 我在控制台窗口中收到此错误: Uncaught TypeError:无法读取未定义的属性“ toLowerCase”
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. 我想知道如何解决我的代码,而不是检查整个字符串,而是检查字符串的一部分,例如说“ Finance”,并且它不区分大小写。
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.