没有.reverse()的情况下,如何在JavaScript中反转16个字符或更少的数组? [英] How do I reverse an array in JavaScript in 16 characters or less without .reverse()?

查看:52
本文介绍了没有.reverse()的情况下,如何在JavaScript中反转16个字符或更少的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决挑战 Codewars要求您以16个字符以内的字符反转JavaScript中的数组.不能使用.reverse().

I'm trying to solve a challenge on Codewars which requires you to reverse an array in JavaScript, in 16 characters or less. Using .reverse() is not an option.

您的代码中允许的最大字符数为28,其中包括函数名称weirdReverse,因此仅剩下16个字符即可解决它.约束-

The maximum number of characters allowed in your code is 28, which includes the function name weirdReverse, so that leaves you with just 16 characters to solve it in. The constraint -

您的代码必须尽可能短,实际上不能超过28个字符

Your code needs to be as short as possible, in fact not longer than 28 characters

样本输入和输出-

输入:包含任何类型的数据的数组.例如:[1,2,3,'a','b','c',[]]

输出:[[],'c','b','a',3,2,1]

给出的入门代码是-

weirdReverse=a=>

我的解决方案( 29 个字符)是-

My solution (29 characters) is -

weirdReverse=a=>a.sort(()=>1)

哪个当然会失败-

代码长度应小于或等于28个字符.

Code length should less or equal to 28 characters.

您的代码长度= 29-预期:代码长度< = 28",而是:代码长度> 28'

your code length = 29 - Expected: 'code length <= 28', instead got: 'code length > 28'

我不确定在这里还要截断什么.

I'm not sure what else to truncate here.

注意-我确实考虑过在 CodeGolf SE 上发布此问题,但由于这种情况,我觉得这不太适合在有限的范围内.

Note - I did think about posting this question on CodeGolf SE, but I felt it wouldn't be a good fit there, due to the limited scope.

推荐答案

我想给您一个提示,但不给您答案:

I'd like to give you a hint, without giving you the answer:

您已经接近了,但是您可以通过 not 使用需要在代码中添加的内容来保存字符.

You're close, but you can save characters by not using something you need to add in your code.

通过添加您不会使用的东西,您可以删除().

By adding the thing you won't use, you can remove ().

扰流器(答案):

// Note: this only really works for this specific case.
// Never EVER use this in a real-life scenario.

var a = [1,2,3,'a','b','c',[]]

weirdReverse=a=>a.sort(x=>1)
//                     ^ That's 1 character shorter than ()

console.log(weirdReverse(a))

这篇关于没有.reverse()的情况下,如何在JavaScript中反转16个字符或更少的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆