简体   繁体   中英

Check for equal quantity of 2 characters in string

Hi I am trying to create a function in JS that takes a string and checks if there are an equal number of "x"s and "o"s in the string.

My code so far (not working):

const checkXo = (str) => {
  const y = 0;
  const z = 0;
  for (let x = 0, x < str.length, x++) {
    if (str.charAt(x) == "o") {
        y++;
    } else if (str.charAt(x) == "x") {
        z++;
    }
    }
    if (y === z) {
    return true;
  } else {
    return false;
}
}

checkXo("xxoo");

const defines a constant, so you won't be able to change values of y and z . Instead, you should use var or let :

let y = 0;
let z = 0;

Consider to do it in a `functional' way:

const checkXo = (str, a, b) =>
  str.split('').filter(s => s === a).length ===
    str.split('').filter(s => s === b).length

test it with

checkXo('xxoo', 'x', 'o')    // return true
checkXo('stackoverflow', 'x', 'o')  // return false

Please note a single line of code can check for equal quantity of any characters of your choice 'a, 'b'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM