I'm trying to write a piece of code that takes an array of strings with spaces containing item names (items) and searches it for a string (str). The code works fine as long as I do not first attempt to convert the array to lowercase so that I can catch all possible cases of the search string. The code in the attached jsfiddle works fine in Firefox but not in WebKit or IE. Can anyone lend any insight?

我正在尝试编写一段代码,该代码采用包含项目名称(项目)的空格的字符串数组,并在其中搜索字符串(str)。代码工作正常,只要我不首先尝试将数组转换为小写,以便我可以捕获搜索字符串的所有可能情况。附加的jsfiddle中的代码在Firefox中运行良好,但在WebKit或IE中运行不正常。任何人都可以提供任何见解吗?

http://jsfiddle.net/Y6zKx/16/

http://jsfiddle.net/Y6zKx/16/


//Array of item names, 0 contains "String"

//项目名称数组,0包含“字符串”

var items = new Array('Item Name Contains String', 'This item is missing it');

//Function searchArray will search for String str in Array of Strings strArray

//函数searchArray将在String of Strings strArray中搜索String str

function searchArray(str, strArray) {
    for (var j = 0; j < strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
}

//Convert the items Array to lowercase so that the search is case-insensitive

//将items数组转换为小写,以便搜索不区分大小写

//This works in Firefox but not in Webkit

//这适用于Firefox,但不适用于Webkit

var lowerCaseItems = $.map(items, String.toLowerCase);
alert(lowerCaseItems);

//This appears to create the same output but doesn't work in either Firefox or Webkit:

//这似乎创建了相同的输出,但在Firefox或Webkit中不起作用:

alert(items.toString().toLowerCase());

//If the array contains "battery" the function will return the positive position

//如果数组包含“电池”,则该函数将返回正位置

contains = searchArray("string", lowerCaseItems);
alert(contains);

//If the id is found, show the message

//如果找到了id,则显示该消息

if ($('#noItems').length) {
    $('#emptyCart').show();
}

//If str is not found show the message

//如果未找到str,则显示该消息

if (contains == -1) {
    $('#noString').show();
}
//else 
else {
    alert("String Found");
}

3 个解决方案

#1


9

Try this:

尝试这个:

var lowerCaseItems = $.map(items, function(n,i){return n.toLowerCase();});

jQuery.map invokes the function on null/window context and passes the item as a parameter to the function. So, passing toLowerCase function won't work as it must be invoked on string object which jQuery.map does not do.

jQuery.map调用null / window context上的函数,并将该项作为参数传递给函数。因此,传递给forLowerCase函数将无法工作,因为它必须在jQuery.map不执行的字符串对象上调用。

更多相关文章

  1. 使用jackson json将属性添加到json字符串
  2. 返回指定时间段相同间隔数组
  3. 如何将带有双引号反斜杠的JSON字符串转换为Javascript对象
  4. JavaScript数组中的唯一计数,按计数排序
  5. Javascript sort()不适用于Chrome中超过10个对象的数组
  6. 获取JavaScript数组元素的最大长度
  7. Javascript正则表达式应该允许空和非空字符串,但它不会
  8. 对多维数组中的列进行排序
  9. 获取拆分字符串数组的最后一个元素

随机推荐

  1. Android基础 : Android(安卓)Content Pro
  2. 高级组件之网格视图
  3. Android系统启动流程(4) —— 解析Launch
  4. Android Studio --- > [学习笔记]Button
  5. 自定义android开机动画
  6. Android源代码目录组成介绍-android学习
  7. android 控件-TextView用法整理
  8. Android(安卓)Studio debug.keystore位置
  9. 【Android布局】在程序中设置android:gra
  10. [转]Jollen 的Android 教學,#1: Android