jQuery JavaScript - 未捕获的类型错误:无法读取未定义的属性“搜索”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29878742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Uncaught TypeError: Cannot read property 'search' of undefined
提问by DELION
When I execute my Javascript I'm getting this error:
当我执行我的 Javascript 我收到这个错误:
Uncaught TypeError: Cannot read property 'search' of undefined
未捕获的类型错误:无法读取未定义的属性“搜索”
And I don't know how do fix it and why that is shown.
我不知道如何修复它以及为什么会显示它。
I have objects inside an array,
我在数组中有对象,
example:
例子:
AsukohaArray = [{"Punkt":[[58.1056],[23.2589]],
"name":"Haapsalu Raamat",
"PunktiID": 23}];
My code
我的代码
$(document).ready(function() {
$("input[type='search']").keyup(function() {
var searchTerm = $(this).val();
var myExp = new RegExp(searchTerm, "i");
var output = "<ul id='result'>";
$.each(AsukohaArray, function(key, val) {
//console.log(val.name);
if ((val.name).search(myExp) != -1) {
output += '<li>';
output += val.name;
output += '</li>';
}
});
console.log(output);
output += "</ul>";
$('div#update').html(output);
});
});
HTML
HTML
<ons-page id="my-page">
<ons-toolbar>
<div class="left">
<ons-toolbar-button ng-click="menu.toggleMenu()"><ons-icon icon="ion-navicon" style="font-size: 32px; width: 1em;"></ons-icon></ons-toolbar-button>
</div>
<div class="center">Kaardi vaade</div>
</ons-toolbar>
<div id="nupuriba">
<input type="search" class="search-input" id="#search">
</div>
<div id="update"></div>
<div id="map-canvas">
</div>
</ons-page>
When I insert "Haapsalu" then results are:
当我插入“Haapsalu”时,结果是:
Haapsalu piiskopilinnus Haapsalu Kunstikool Haapsalu Raamat Uncaught TypeError: Cannot read property 'search' of undefined
Haapsalu piiskopilinnus Haapsalu Kunstikool Haapsalu Raamat Uncaught TypeError:无法读取未定义的属性“搜索”
I have searched that error, but no result, haven't found nothing similar.
我搜索了那个错误,但没有结果,没有发现任何类似的东西。
采纳答案by Laurentiu Petrea
Is your "val" (item from the array) a primitive data type, or is it an object containing the attribute "name"? If your val is let's say a String type, you should "search" directly into it. Your error suggests that "val" does not contain an attribute called "name".
您的“val”(数组中的项目)是原始数据类型,还是包含属性“name”的对象?如果你的 val 是一个 String 类型,你应该直接“搜索”它。您的错误表明“val”不包含名为“name”的属性。
Also, since you are using a RegExp, there, you should probably go with
另外,由于您使用的是 RegExp,因此您可能应该使用
if( val.match(myExp) > 0 )
or even better, if you only care about a boolean result,
甚至更好,如果您只关心布尔结果,
if ( val.test(myExp) )
If I am wrong, and your .name attribute exists, if it's a string, just use it directly without the parenthesis:
如果我错了,并且您的 .name 属性存在,如果是字符串,则直接使用它,无需括号:
if( val.name.test(myExp) )
回答by renakre
Can you try
你能试一下吗
if(val.indexOf(myExp) != -1){
instead of
代替
if(val.search(myExp) != -1){