在JavaScript中使用MAP()时,在元素上使用字符串函数?
我正在尝试执行以下操作。
strs = ["one", "two"];
let sorted_str = strs.map((s) => [s.sort(), s]);
本质上,我要做的是创建一个新的数组数组,其中这个新数组就像 [从第一个数组中排序的字符串,第一个数组中的原始字符串]
但是,它看起来像 .sort()
方法在这里无效。
我什至尝试使其
let sorted_str = strs.map((s) => [s.toString().sort(), s]);
强制串起字符串,并确保它具有 sort()
方法,但无济于事。
错误是 typeError:s.tostring(...)。排序不是函数
。
无论如何,我都可以将其工作或任何简单的解决方法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要获得一系列字符,对其进行排序并恢复字符串。
You need to get an array of characters, sort it and get a string back.
您需要转换为数组,然后应用排序方法,然后再次加入字符串,尝试以下操作:
You need to convert to array, then apply the sort method, and then join to a string again, try this:
而不是使用
split()
。 请勿使用split()instead of using
split()
. do not use split()字符串类没有
.sort()
方法。阵列类会做!因此,您可以将字符串转换为数组,对其进行排序,然后将排序的数组转换回字符串。看起来像The String class does not have a
.sort()
method. The array class does, though! So you can convert the string to an array, sort that, and then convert the sorted array back to a string. That would look something likesort()
方法需要一个数组作为输入,但是如果您在回调函数中调用它传递给map()
,则在单个字符串上调用它。我不是100%确定我了解所需的输出,无论如何这是我的解决方案。
让我们从要分类的一系列字符串开始。
现在,为了对其进行排序而无需突变,我们可以做:
现在,我们有两个阵列,一个原始的阵列,另一个带有排序字符串。
我们可以使用
map()
在原始数组上循环并创建所需的数组。索引
回调函数中的参数可用于检索排序的数组中的项目。现在,如果我正确理解我们需要您所需的内容:
如果您愿意,您可以将所有内容放在一个函数中:
您可以这样称呼:
The
sort()
method needs an array as input, but if you call it in the callback function passed to amap()
you are calling it on a single string.I'm not 100% sure that I understood the desired output, anyway here is my solution.
Let's start with an array of Strings that we want to sort.
Now in order to sort it without mutating it we can do:
Now we have two arrays, the original one, and another one with the sorted strings.
We can use
map()
to loop over the original array and to create the array that you need. Theindex
parameter in the callback function can be used to retrieve the item in the sorted array.Now if I understood correctly we have what you needed:
If you want you can put everything together in one function:
That you can call like this: