简体   繁体   中英

How can I combine the functions in Javascript

I am busy learning and trying. But I fail again because of such little things. I want to make isValidCard shorter. I thought I can now simply enter toName and toSuit because it is defined above. But that doesn't work.

'use strict';
const NAMES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const SUIT = ['A', 'B', 'C', 'D'];

const toSuit = (number) => number.charAt(number.length - 1); 
const toName = (number) => number.slice(0, -1); 

const isValidCard = (number) =>
  NAMES.includes(number.slice(0, -1)) === SUIT.includes(number.charAt(number.length - 1));

console.log(isValidCard('9A')); // => true
console.log(isValidCard('11A')); // => false
console.log(isValidCard('9X')); // => false

my attempt which did not work:

'use strict';
const NAMES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const SUIT = ['A', 'B', 'C', 'D'];
    
const toSuit = (number) => number.charAt(number.length - 1); //nur das letzte Zeichen ausgeben
const toName = (number) => number.slice(0, -1); //das letzte Zeichen bei Ausgabe weglassen
    
const isValidCard = (number) =>
  NAMES.includes(toName) === SUIT.includes(toSuit);

console.log(isValidCard('9A')); // => true
console.log(isValidCard('11A')); // => false
console.log(isValidCard('9X')); // => false

You need a logical AND && for comparing both values to be true , or at least truthy .

BTW, a good idea is to choose variable names according to the content, in this case take better card instead of number , which is misleading and confusing, because there is no number in it.

 'use strict'; const NAMES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], SUIT = ['A', 'B', 'C', 'D'], toSuit = card => card.slice(-1), toName = card => card.slice(0, -1), isValidCard = card => NAMES.includes(toName(card)) && SUIT.includes(toSuit(card)); console.log(isValidCard('9A')); // => true console.log(isValidCard('11A')); // => false console.log(isValidCard('9X')); // => false

If I understood what you want to achieve as per the first code output, you just need to pass the number param inside the function that you created.

Just update the below code:

const isValidCard = (number) =>
  NAMES.includes(toName(number)) === SUIT.includes(toSuit(number));

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