【问题标题】:How to check lowercase in indexOf如何检查 indexOf 中的小写字母
【发布时间】:2015-10-06 11:24:44
【问题描述】:

这里 diseaseList 是一个数组。

for(var i=0;i<_list.length;i++)
{
    if($scope.diseaseList.indexOf(_list[i].disease) != -1){
        _list[i].favorite = true;
    }else{
        _list[i].favorite = false;
    }
}

我想做这样的事情

if($scope.diseaseList.toLoweCase().indexOf(_list[i].disease.toLoweCase()) != -1){

但它会抛出错误,因为$scope.diseaseList 是一个数组。我可以删除indexOf 并再使用一个循环,但我不想这样做。任何其他选项 请提出建议。

【问题讨论】:

  • angular.lowercase(_list[i].disease); ?
  • 将数组转换为小写
  • 如果你想在数组上调用 .toLowerCase() ,那么你需要先对数组原型进行猴子补丁..

标签: javascript jquery angularjs


【解决方案1】:

数组没有toLowerCase(请注意,您的代码中有一个错字:缺少r)函数。但是您可以使用map 函数并返回小写值。它的工作原理是这样的:

["Foo", "BaR"].map(function (c) { return c.toLowerCase(); });
// => ["foo", "bar"]

在您的代码中,可以像下面这样应用:

if($scope.diseaseList.map(function (c) {
    return c.toLowerCase();
   }).indexOf(_list[i].disease.toLowerCase()) != -1) { ... }

此外,您可以删除 != -1 并将其更改为使用按位运算符:

if(~$scope.diseaseList.map(function (c) {
    return c.toLowerCase();
   }).indexOf(_list[i].disease.toLowerCase())) { ... }

@Tushar 有另一个有趣的解决方案,可以将字符串数组转换为小写:

String.prototype.toLowerCase.apply(arr).split(',');

【讨论】:

  • 应该是return c.toLowerCase();(注意额外的rLower)。
  • String.prototype.toLowerCase.apply(arr).split(',');也可以使用
  • @Tushar 谢谢。添加它来回答。 :) 不确定它是如何在浏览器中工作的(如果我没记错的话,IE 在字符串化数组中存在一些问题)。但它很可爱。
  • @IonicăBizău 你也可以使用arr.map(String.prototype.toLowerCase.call.bind(String.prototype.toLowerCase));stackoverflow.com/questions/33006222/…
猜你喜欢
  • 2011-02-18
  • 2011-02-19
  • 1970-01-01
  • 2013-04-14
  • 2012-10-07
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多