admin管理员组

文章数量:1289889

In c#, I create an array of vowels then use it to pare whether the string contains any of the elements of the array, but I don't know how to do it in JavaScript. I use .Contains() to find whether the next character of string word is vowel or not. If the next char of word is vowel, make it upper case and concatenate to the string result, otherwise, just concat it to the string result without changing the casing.

Here is my implementation in c#:

static string Reverser(string word)
{
    //string[] vowels = { "a", "e", "i", "o", "u" };
    List<string> vowels = new List<string>{ "a", "e", "i", "o", "u" };
    string result = "";

    for (int i = word.Length-1; i >= 0; i--) {

        if (vowels.Contains(word[i].ToString()))
        {
            result += word[i].ToString().ToUpper();
        }
        else
        {
            result += word[i].ToString();
        }
    }


    return result;
}

I tried researching but the search only tells me about includes.

In c#, I create an array of vowels then use it to pare whether the string contains any of the elements of the array, but I don't know how to do it in JavaScript. I use .Contains() to find whether the next character of string word is vowel or not. If the next char of word is vowel, make it upper case and concatenate to the string result, otherwise, just concat it to the string result without changing the casing.

Here is my implementation in c#:

static string Reverser(string word)
{
    //string[] vowels = { "a", "e", "i", "o", "u" };
    List<string> vowels = new List<string>{ "a", "e", "i", "o", "u" };
    string result = "";

    for (int i = word.Length-1; i >= 0; i--) {

        if (vowels.Contains(word[i].ToString()))
        {
            result += word[i].ToString().ToUpper();
        }
        else
        {
            result += word[i].ToString();
        }
    }


    return result;
}

I tried researching but the search only tells me about includes.

Share Improve this question edited Jul 1, 2018 at 22:12 Pamingkas Sevada asked Jul 1, 2018 at 2:15 Pamingkas SevadaPamingkas Sevada 4329 silver badges22 bronze badges 2
  • Your algorithm is inefficient because it runs in O( n * m ) time (where n is string length and m is the number of vowels). You should use a O( 1 ) lookup structure like an array indexed by character value. – Dai Commented Jul 1, 2018 at 2:18
  • I think you're looking for either string.includes() or array.includes(). – Leland Jobson Commented Jul 1, 2018 at 2:24
Add a ment  | 

3 Answers 3

Reset to default 9

In c#, I create an array of vowels then use it to pare whether the string contains any of the elements of the array, but I don't know how to do it in JavaScript.

Rather than directly adapt your algorithm (using an array of vowels as strings) to JavaScript, I felt it'd be better to show you a much faster algorithm.

Generally speaking indexed vector-type structures (like Array, ArrayList, and List<T> in .NET) are bad for "contains" tests because the program has to check every value for a match (i.e. O(n) time), whereas structures like a Hashtable (Dictionary<TKey,TValue>) or HashSet<T> have O(1) time for the same "contains" operation.

So the algorithm should do this:

  1. Have a pre-generated set (in the mathematical sense) of known vowels.
  2. For each character in the string, check to see if that character is in the set from step 1.
  3. (And from your code, but not your post, I see you build a new output string where vowels are capitalized - this can be done efficiently with a StringBuilder instead of String += because it avoids excess string allocation and buffer-copy operations).

Here's the algorithm in C#:

String word = "hello, world.";
HashSet<Char> vowels = new HashSet<Char>( new[] { 'a', 'e', 'i', 'o', 'u' } );
StringBuilder output = new StringBuilder();
foreach( Char c in word )
{
    if( vowels.Contains( c ) ) sb.Append( Char.ToUpper( c ) );
    else sb.Append( c );
}

In JavaScript there isn't a HashSet<T> type (UPDATE: There is now), nor are there Char values (only strings, the string.charAt function returns a single-character string value). However, in Javascript, all Object2 values are keyed-dictionaries with (ideally) O(1) member lookup by name - so you can use a new Object to store the set of known vowels as keys (with dummy integer values) and then iterate through each character in the string. Another unfortunate quirk of JavaScript is the lack of a StringBuilder so we have to stick with += concatenation (though some JS environments do optimize this with an internal StringBuilder-like feature, this is not part of the ECMAScript language spec):

var vowels = { 'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0 };
var word = "hello, world.";
var output = "";
for( var i = 0; i < word.length; i++ ) {
    var c = word.charAt( i );
    if( c in vowels ) { // this operation is O(1)
        // character is a vowel
        output += c.toUpperCase();
    }
    else {
        output += c;
    }
}

2: JavaScript Object and .NET's System.Object are pletely unrelated besides simply sharing the same name. In .NET it's a mon superclass for all reference-types, whereas in JavaScript it's a name/value collection structure.

Use includes in js.

var hasWord = "this is a sample text.".includes("text");

Since you said the only thing you can find is includes, this tells me that you are looking for something else. I think what you are looking for is indexOf. You can use indexOf to see if an array value is also present in another array. If it is, it returns the values index, if it isn't it returns -1. This is the way I wrote this:

  var testWords = [ 'a', 'b', 'c', 'd'];

  function reverser(words){
    var result = '';
    words.forEach((word) => {
      if(testWords.indexOf(word) > -1){
        result += word;
      }
    })
    console.log(result);
  };

  reverser(['b', 'd', 'e', 'z']);

If you are entering an actual string and just trying to see if each letter is a key in an object, then you could do something like this:

  function reverserObj(word){
    var result = '';
    var splitWords = word.split("");
    var obj = {a:0, e:0, i:0, o:0, u:0};
    splitWords.forEach((letter) => {
      console.log(letter);
      if(obj.hasOwnProperty(letter)){
        result += letter;
      }
    });

    console.log(result);
  }

  reverserObj('hello world');

Take a look at these really, really great javascript functions. You can do all sorts of things with these. https://underscorejs/#

本文标签: javascriptIs there a js equivalent to Contains of cStack Overflow