【问题标题】:How can I find all the elements in javaScript array that start with certain letter如何找到以某个字母开头的javascript数组中的所有元素
【发布时间】:2015-05-13 09:36:27
【问题描述】:

有什么方法可以过滤出数组中以字母 a 开头的项目。即

var fruit = 'apple, orange, apricot'.split(',');
  fruit = $.grep(fruit, function(item, index) {
  return item.indexOf('^a'); 
  });
alert(fruit);

【问题讨论】:

  • 在 jQuery 中试试这个:var $beginswitha = $(":input[name^='a']")。然后将该变量放在您的 indexOf 语句中。

标签: javascript jquery arrays indexof


【解决方案1】:

三件事:

  • 你想用', '分割,而不是','
  • indexOf 不采用正则表达式,而是一个字符串,因此您的代码将搜索文字 ^。如果您想使用正则表达式,请使用 search
  • indexOf(和search)确实会返回他们找到热门术语的索引。您必须将其与您的期望进行比较:== 0。或者,您可以使用返回布尔值的正则表达式 test 方法。

alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
    return item.indexOf('a') == 0; 
}));
alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
    return /^a/.test(item); 
}));

【讨论】:

    【解决方案2】:

    在检查之前,您必须 trim item 中的空格。

    正则表达式检查是否以:^a开头

    var fruit = 'apple, orange, apricot'.split(',');
    fruit = $.grep(fruit, function (item, index) {
        return item.trim().match(/^a/);
    });
    alert(fruit);
    

    其他解决方案:

    var fruits = [];
    $.each(fruit, function (i, v) {
        if (v.match(/^a/)) {
            fruits.push(v);
        }
    });
    alert(fruits);
    

    【讨论】:

    • 太棒了。非常感谢。我对 javascript 很陌生,非常感谢
    【解决方案3】:

    你可以像这样使用charAt

    var fruit = 'apple, orange, apricot'.split(', ');
      fruit = $.grep(fruit, function(item, index) {
      return item.charAt(0) === 'a';
    });
    alert(fruit);
    

    【讨论】:

    • 太棒了。为此干杯
    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2016-12-17
    • 2011-11-02
    • 2021-06-16
    • 2018-07-20
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多