简体   繁体   English

数组拼接-Javascript

[英]Array Splice - Javascript

Its a very small issue and for the life of me I can't figure out what it is. 这是一个很小的问题,对于我的一生,我不知道这是什么。 My brain has locked itself from thinking. 我的大脑使自己无法思考。 I need someone else to have a look this code. 我需要其他人看一下此代码。

The output of the code should be: [1,0,0,0] 代码的输出应为: [1,0,0,0]

UPDATE: 更新:

The function should be able to read an array of numbers and if it finds any zeros within the array it should move them to the end of the array. 该函数应该能够读取数字数组,如果在数组中找到任何零,则应将它们移到数组末尾。

The output of the code keeps coming as: [0,1,0,0] 代码的输出一直为: [0,1,0,0]

var arrNum = [0,0,0,1];

function test() {
   for(var i=0; i<arrNum.length; i++){

 if(arrNum[i] == 0){

    arrNum.splice(i,1)
    arrNum.splice(arrNum.length, 1, 0)

    }
 }
 return alert(arrNum)
}

Here is a working plunker. 是一个工作的小伙子。

Apologies for this, I know the issue is something very small but my brain has stopped working now and I need a fresh pair of eyes. 对此表示歉意,我知道问题很小,但是我的大脑现在停止工作了,我需要换新的眼睛。

With the way you have it written, you need to loop in the reverse order. 用编写的方式,您需要以相反的顺序循环。 You end up skipping indexes when you remove the index. 当您删除索引时,最终将跳过索引。 Looping in the reverse direction keeps you from skipping them. 反向循环可避免您跳过它们。

for(var i=arrNum.length-1; i>=0; i--){ 

You can use unshift() to insert at beginning of an array and push() to the end... 您可以使用unshift()插入数组的开头,然后将push()插入结尾。

    var arrNum = [0,0,0,1];
    var output = [];

    function test() 
    {
       for(var i=0; i<arrNum.length; i++)
       {
         if(arrNum[i] == 0)
            output.push(0);
         else
            output.unshift(arrNum[i]);
     }
     return alert(output)
    }
var arrNum = [0,0,0,1];
var result = [];

arrNum.forEach(function(v) {
    !!v ? result.unshift(v) : result.push(v);
});

console.log(result);

You are iterating with index i = 0,1,2,3 and at the same time removing first elements of array. 您正在使用索引i = 0、1、2、3进行迭代,同时删除数组的第一个元素。 So your iteration can not see the 1, it jumps over as it is moved to already iterated index. 因此,您的迭代看不到1,它在移至已迭代的索引时会跳过。 Easiest would be to just reverse the loop to bypass the issue. 最简单的方法是反转循环以绕过此问题。

var arrNum = [0,0,0,1];

function test() {
  for(var i= arrNum.length; i >= 0; i--){

    if(arrNum[i] == 0){
      arrNum.splice(i,1)
      arrNum.splice(arrNum.length, 1, 0)
    }
  }
  return alert(arrNum)
}

Prefer built-in functions every time possible. 尽可能使用内置函数。

var output = [];
[0,0,0,1].forEach(function(num) {
  if(num == 0) output.push(0);
  else output.unshift(num)
})

Why don't you use a temporary array to help? 您为什么不使用临时数组来提供帮助? The problem with your code is that the splice() function modifies the original array, and you are doing it inside the loop. 您的代码的问题在于splice()函数会修改原始数组,并且您正在循环内进行操作。

The code below produces what you need: 下面的代码产生您所需要的:

var arrNum = [0,0,0,1];
var arrResult = new Array();

function test() {

   for(var i=arrNum.length-1; i>=0; i--)
   {
        arrResult.push(arrNum[i]);
   }

   arrNum = arrResult;
   return alert(arrNum);
}

With another array to store the new values, you gain flexibility to do whatever you need with the data of the first array. 使用另一个存储新值的数组,您可以灵活地对第一个数组的数据执行所需的任何操作。

A nice little way using Objects - busy learning them so just posting a variation of deligation 使用对象的一种不错的小方法-忙着学习它们,所以只需发布一个变体

var methods = {
    moveZero: function(arr){
        //console.log(arr);
        var newArr = [];
        for(var i  = 0; i < arr.length; i++){
            if(arr[i] === 0){
                newArr.push(arr[i]);
            }else{
                newArr.unshift(arr[i]);
            }
        }
        console.log(newArr);
    }
}

var arrNum = Object.create(methods);
arrNum.moveZero([0,0,50,56,85,0,0,43,10,0,1]);

JSFiddle - https://jsfiddle.net/ToreanJoel/qh0xztgc/1/ JSFiddle- https: //jsfiddle.net/ToreanJoel/qh0xztgc/1/

The problem was you are modifying an array while looping over it in if statement. 问题是您在if语句中循环时正在修改数组。

Here is a working plunker of your example. 是您的示例的一个有用的工具。

var len = arrNum.length;
var index = 0;

while(len) {

    if(arrNum[index] == 0) {
        arrNum.splice(index,1);
        arrNum.push(0);
    } else {
        ++index;
    }

    --len;
}

As the operation you want to do is actually sorting, for readability and compactness of code maybe you should be doing this instead: 由于您要执行的操作实际上是排序,因此为了代码的可读性和紧凑性,您应该这样做:

var arrNum = [0,1,0,0]; 
arrNum.sort(function(a, b) {
  return a == 0 ? 1 : 0;
});

It can contain any number and will keep order of others than 0 它可以包含任何数字,并保持除0以外的其他顺序

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

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