从javascript数组中查找匹配的字符串

从javascript数组中查找匹配的字符串

本文介绍了从javascript数组中查找匹配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组.我需要找到所有以键开头的字符串.例如:如果有数组['apple','ape','open','soap']使用关键字"ap"搜索时我应该只得到苹果"和猿",而不是肥皂".

I have one array of strings. I need to find all strings starting with a key.for eg: if there is an array ['apple','ape','open','soap']when searched with a key 'ap'i should get 'apple' and 'ape' only and not 'soap'.

这是在javascript中.

This is in javascript.

推荐答案

function find(key, array) {
  // The variable results needs var in this case (without 'var' a global variable is created)
  var results = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i].indexOf(key) == 0) {
      results.push(array[i]);
    }
  }
  return results;
}

这篇关于从javascript数组中查找匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 03:31