如何解决数组中的javascript映射问题



我还在打牌。我一次又一次地遇到这样的地方,我再也走不动了。我有两只手在打牌。我想将名称和套装输出为一个数组。但这只适用于两位数的组合。只要有一个10,它就是三位数,它就不再工作了。

'use strict'
let hand1 = ['7H', '2H', 'QH', '9H', '5H']
let hand2 = ['7H', '2H', 'QH', '10H', '5H']
let toSuit = hand => hand.map(a => a[0])
let toName = hand => hand.map(a => a[1])

console.log(toName(hand1))
console.log(toSuit(hand1))
console.log(toName(hand2))
console.log(toSuit(hand2))

我可以对单个卡执行此操作,但不能对作为数组的输出执行此操作。

'use strict'

let card1 = '9H'
let card2 = '10H'

let toSuit1 = card => card.charAt(card.length - 1)
let toName1 = card => card.slice(0,-1)  

console.log(toSuit1(card1))
console.log(toSuit1(card2))
console.log(toName1(card1))
console.log(toName1(card2))

感谢@blex

'use strict'
let hand1 = ['7H', '2H', 'QH', '9H', '5H']
let hand2 = ['7H', '2H', 'QH', '10H', '5H']
let toSuit1 = card => card.charAt(card.length - 1);
let toName1 = card => card.slice(0,-1); 
let toSuit = hand => hand.map(toSuit1)
let toName = hand => hand.map(toName1)
console.log(toName(hand1))
console.log(toSuit(hand1))
console.log(toName(hand2))
console.log(toSuit(hand2))

您可以只使用函数进行映射。

'use strict';
const
toSuit = card => card.charAt(card.length - 1),
toName = card => card.slice(0,-1),
toSuits = hand => hand.map(toSuit),
toNames = hand => hand.map(toName),
hand1 = ['7H', '2H', 'QH', '9H', '5H'],
hand2 = ['7H', '2H', 'QH', '10H', '5H'];
console.log(...toNames(hand1))
console.log(...toSuits(hand1))
console.log(...toNames(hand2))
console.log(...toSuits(hand2))

最新更新