简体   繁体   English

如何从数组项中删除字符?

[英]How to remove characters from an array item?

I have a function which generate random poker hand and after that I want to delete all the suits and just leave numbers to the array. 我有一个生成随机扑克手的函数,此后我想删除所有花色,只剩下数字到数组中。 What is the easiest way to do that? 最简单的方法是什么? I have tried different things without any good results. 我尝试了不同的方法,但没有任何良好的结果。

For example array could be something like this: 例如,数组可能是这样的:

test = ["5♥","7♦","6♠","9♥","10♣"];

but I want it to be like this: 但我希望它是这样的:

test = ["5","7","6","9","10"];

I wanna emphasize that in this case I have no idea what kind of array it would be when the function generate the array and delete the suits. 我想强调的是,在这种情况下,我不知道当函数生成数组并删除西装时它将是什么样的数组。

Thank you for your help! 谢谢您的帮助!

You can use map() and use slice() to remove the last element of string. 您可以使用map()slice()删除字符串的最后一个元素。

 const test = ["5♥","7♦","6♠","9♥","10♣"]; const res = test.map(x => x.slice(0,-1)); console.log(res) 

You could remove the last character of each string. 您可以删除每个字符串的最后一个字符。

 let test = ["5♥","7♦","6♠","9♥","10♣"]; let out = test.map(a => a.slice(0, -1)); console.log(out); 

You can use regex , 您可以使用regex,

 let test = ["5♥","7♦","6♠","9♥","10♣"]; console.log(test.map(str => str.replace(/.$/, ''))); 

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

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