Javascript中的“阵列左旋转"将记录到控制台,但不会返回 [英] Array Left Rotation in Javascript will log to console but not return

查看:65
本文介绍了Javascript中的“阵列左旋转"将记录到控制台,但不会返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理Hackerrank上的数组左旋转.我拥有的解决方案将console.log包含正确结果的数组,但无法使用return起作用.这是他们网站上的详细信息-在执行d次左旋转后,打印一行n个以空格分隔的整数,这些整数表示数组的最终状态."我已经读到问题可能出在node.js中运行的异步函数,但是我不确定如何解决.

I'm working on the array left rotation on Hackerrank. The solution that I have will console.log the array containing the correct result, but will not work using return. Here's the detail from their site - "Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations." I've read that the issue might be with asynchronous functions running in node.js, but I'm not sure how to work around that.

// sample input - 1 2 3 4 5
// sample output - 5 1 2 3 4

function rotLeft(a, d) {
  var arr = [];

    for (var i = 1; i <= a; i++){
      arr.push(i)
    };
    for (var j = 1; j <= d; j++){
    	arr.shift(arr.push(j))
    }
    console.log(arr.toString()); // <-- this will print the desired output.
    return arr.toString(); // <-- no return from this.
}


rotLeft(5, 4)

推荐答案

我也一直在尝试解决此问题.您当前的解决方案中存在一些问题.看到您必须创建一个数组并将从参数传递过来的数组存储在其中. 您所做的只是创建一个新数组并添加其中应该包含的元素数量的顺序,例如您正在执行arr.push 1 2 3 4 5.但问题是要有一系列用户选择.第二件事是您应该返回一个数组而不是字符串.

I have also been trying to solve this problem. There are some issues in your current solution. See you have to create an array and store the array passed from parameters in it. What you have done is just creating a new array and adding the sequence of numbers of elements that should be in it e.g a.length=5 you are doing arr.push 1 2 3 4 5. But the question wants an array of user's choice. Second thing is that you should return an array not the string.

这是此问题的解决方案:

So this is the solution of this problem:

function rotLeft(a, d) {
    var arr = [];
    for (var i = 0; i < a.length; i++) {
        arr.push(a[i]);
    };
    for (var j = 1; j <= d; j++) {
        arr.shift(arr.push(arr[0]));
    }
    return arr;
}

这篇关于Javascript中的“阵列左旋转"将记录到控制台,但不会返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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