将项目返回到数组中

时间:2016-01-29 02:51:36

标签: javascript arrays splice

试图解决卷心菜,狼和山羊的问题。我的游戏计划是创建两个阵列,一个代表河岸的左侧,另一个代表右侧。基本上,如果阵列中的两个项目相互威胁,例如,如果左侧阵列包含山羊和卷心菜,则不允许将狼移出。我已经设置了我的数组,但是当我调用函数返回项目(卷心菜,狼,山羊)时,它不会将它放回到leftSide数组中。我正在使用splice()来重新添加项目。这是问题吗?这是我试图做的事情:

function returnCabbage(){
    $("#cabbage2").hide();
    $("#cabbage").show();
    leftBank.splice(0, 1, cabbage.name);
    rightBank.splice(0, 1);

    console.log(leftBank.length);

    console.log(cabbage.name + " on left bank: " +   isOnLeftBank(cabbage.name));
    console.log(cabbage.name + " on right bank: " + isOnRightBank(cabbage.name));
}

function sendCabbage(){
    $("#cabbage2").show();
    $("#cabbage").hide();
    leftBank.splice(0, 1);
    rightBank.splice(0, 1, cabbage.name);

    console.log(rightBank.length);

    console.log(cabbage.name + " on left bank: " + isOnLeftBank(cabbage.name));
    console.log(cabbage.name + " on right bank: " + isOnRightBank(cabbage.name));
}

此处有更多详细信息:https://jsfiddle.net/Amidi/m7vb3eoj/6/(图片不会加载,页面格式也会关闭)。

1 个答案:

答案 0 :(得分:1)

当你拼接放置时,你正在替换数组中的元素。当您拼接删除时,您将减少数组的长度。相反,您可以使用push来推送阵列。问题是您的代码假定每个元素的特定位置。我会推荐一种略有不同的方法。以下是我推荐的更多内容。我离开了检查失败状态等等。

/* true for left false for right */
var river = {
  cabbage: true,
  wolf: true,
  goat: true
}

function sendItem(name) {
  river[name] = !river[name];
  setState();
};

function setState() {
  Object.keys(river).forEach(function(k) {
    if (river[k] === true) {
      $('.left .' + k).show();
      $('.right .' + k).hide();
    } else {
      $('.left .' + k).hide();
      $('.right .' + k).show();
    }
  });
}

setState();
.river,
.btn-group {
  display: flex;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  flex-flow: row;
  justify-content: space-between;
}
.left,
.right {
  display: flex;
  flex-flow: column;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="river">
  <div class="left">
    <div class="cabbage">Cabbage</div>
    <div class="wolf">Wolf</div>
    <div class="goat">Goat</div>
  </div>

  <div class="right">
    <div class="cabbage">Cabbage</div>
    <div class="wolf">Wolf</div>
    <div class="goat">Goat</div>
  </div>
</div>
<div class="btn-group">
  <button type="button" onclick="sendItem('cabbage')">Send Cabbage</button>
  <button type="button" onclick="sendItem('wolf')">Send Wolf</button>
  <button type="button" onclick="sendItem('goat')">Send Goat</button>
</div>