不使用.shift()方法将JavaScript数组向左移动一个点。算法挑战

时间:2022-06-24 21:24:11

I'm stuck on this algorithm challenge and can't figure out a way to do it. I'm trying to avoid using the .shift() method.

我坚持这个算法挑战,无法找到一种方法来做到这一点。我试图避免使用.shift()方法。

Let's say I have an array of "var x = [1,5,10,7,-2]" and what i'm trying to do is shift it one spot to the left while deleting the first item in the array which is "1". Also I would like to add 0 to the end of the array to replace the spot. The goal is to make the array to be "var x = [5,10,7,-2,0]", I would imagine using a for loop to achieve this. So i'm basically swapping out the first member of the array and swapping in 0 at the end of the array.

假设我有一个“var x = [1,5,10,7,-2]”数组,我想要做的是将它移到左边一个点,同时删除数组中的第一个项目“1”。另外我想在数组的末尾添加0以替换该点。目标是使数组为“var x = [5,10,7,-2,0]”,我想用一个for循环来实现这个目的。所以我基本上交换了数组的第一个成员,并在数组的末尾交换为0。

I'm not allowed to use reverse or sort method. The only method i'm allowed to use with this problem is .length. .pop, or .push. I can also use the for loop and if else statements. These are what I am limited to.

我不允许使用反向或排序方法。我允许使用这个问题的唯一方法是.length。 .pop或.push。我也可以使用for循环和if else语句。这些是我的限制。

3 个解决方案

#1


You could use a for loop

你可以使用for循环

for(var i = 1; i < x.length; i++) {
  x[i-1] = x[i];
}

x[x.length-1] = 0;

#2


Or even shorter...

甚至更短......

for (var i = 0; i < x.length; i += 1) {
    x[i] = x[i + 1] || 0;
}

#3


If you wish to maintain sparse arrays and only have a loop at your disposal, then the algorithm needs to test for members before copying them:

如果您希望维护稀疏数组并且只有一个循环可供使用,那么算法需要在复制之前测试成员:

function shiftLeft(arr) {
  for (var i=1, iLen=arr.length; i<iLen; i++) {
    if (arr.hasOwnProperty(i)) {
      arr[i-1] = arr[i];
    } else {
      delete arr[i-1];
    }
  }
  arr[i-1] = 0;
  return arr;
}

which can be reduced to:

可以减少到:

function shiftLeft(arr) {
  for (var i=1, iLen=arr.length; i<iLen; i++) {
    arr.hasOwnProperty(i)? arr[i-1] = arr[i] : delete arr[i-1];
  }
  arr[i-1] = 0;
  return arr;
}

Which is less code but not as simple and probably slower.

这是更少的代码,但不是那么简单,可能更慢。

#1


You could use a for loop

你可以使用for循环

for(var i = 1; i < x.length; i++) {
  x[i-1] = x[i];
}

x[x.length-1] = 0;

#2


Or even shorter...

甚至更短......

for (var i = 0; i < x.length; i += 1) {
    x[i] = x[i + 1] || 0;
}

#3


If you wish to maintain sparse arrays and only have a loop at your disposal, then the algorithm needs to test for members before copying them:

如果您希望维护稀疏数组并且只有一个循环可供使用,那么算法需要在复制之前测试成员:

function shiftLeft(arr) {
  for (var i=1, iLen=arr.length; i<iLen; i++) {
    if (arr.hasOwnProperty(i)) {
      arr[i-1] = arr[i];
    } else {
      delete arr[i-1];
    }
  }
  arr[i-1] = 0;
  return arr;
}

which can be reduced to:

可以减少到:

function shiftLeft(arr) {
  for (var i=1, iLen=arr.length; i<iLen; i++) {
    arr.hasOwnProperty(i)? arr[i-1] = arr[i] : delete arr[i-1];
  }
  arr[i-1] = 0;
  return arr;
}

Which is less code but not as simple and probably slower.

这是更少的代码,但不是那么简单,可能更慢。