简体   繁体   English

如何组合 Javascript 中的功能

[英]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.我想让 isValidCard 更短。 I thought I can now simply enter toName and toSuit because it is defined above.我想我现在可以简单地输入 toName 和 toSuit,因为它是上面定义的。 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 .您需要一个逻辑 AND &&来比较两个值是否为true ,或者至少为true

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.顺便说一句,一个好主意是根据内容选择变量名,在这种情况下使用更好的card而不是number ,这会产生误导和混淆,因为其中没有数字。

 '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.如果我根据第一个代码 output 了解您想要实现的目标,您只需在您创建的 function 中传递数字参数。

Just update the below code:只需更新以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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