while循环在第一次迭代时停止

时间:2017-11-22 09:39:42

标签: javascript multidimensional-array while-loop

我试图添加匹配数组的所有数字并删除重复的名称。它适用于第一个实例,但while循环不会超过Apples。

function updateInventory(arr1, arr2) {

   function alphabetizer(a, b) {
   if (a[1] < b[1]) return -1;
   if (a[1] > b[1]) return 1;
   return 0;
   }

  var newInv = arr1.concat(arr2).sort(alphabetizer);


  for(i=0;i<newInv.length;i++){

    while(newInv[i][1] != -1){
      newInv[i][0] += newInv[i+1][0];
      newInv.push([newInv[i][0], newInv[i][1]]);
      newInv.splice(i,2);
      return newInv;
    }
    return newInv;
  }

    return newInv;
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"],
    [10, "Apples"]
];

var newInv = [
    [9, "Apples"],
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);

所以,当我运行这个时,我最终得到了

[[21,"Bowling Ball"],[67,"Bowling Ball"],[2,"Dirty Sock"],[1,"Hair Pin"],[2,"Hair Pin"],[3,"Half-Eaten Apple"],[5,"Microphone"],[7,"Toothpaste"],[19,"Apples"]]

2 个答案:

答案 0 :(得分:2)

问题是因为您从FUNC1_DIR = # The directory where your func1.c is located, maybe src/ or something alike $(OBJ_DIR)%.o : $(FUNC1_DIR)%.c gcc $(FLAGS) -I $(HEADER_DIR) -c $< -mv $(@F) $(OBJ_DIR) 循环返回。它终止了循环的进一步执行。从whilereturn循环中删除for部分。并且还使用while关键字声明变量i,以使其作用于函数,而不是全局。

var

答案 1 :(得分:0)

这使它工作,添加var j = i并更改一些代码。

function updateInventory(arr1, arr2) {

    function alphabetizer(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;

        return 0;    
    }

    var newInv = arr1.concat(arr2).sort(alphabetizer);

    for (var i = 0; i < newInv.length; i++) {
        var j = i;
        while (newInv[j + 1] && newInv[j][1] == newInv[j + 1][1]) {
            newInv[j][0] += newInv[j + 1][0];
            newInv.splice(j + 1, 1);
            j++;
        }
    }

    document.getElementById('test').innerHTML = newInv.join('<br>');
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"],
    [10, "Apples"]
];

var newInv = [
    [9, "Apples"],
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);