拼接不从数组javascript中删除项目

时间:2015-08-21 03:51:13

标签: javascript splice

我的代码中遇到splice问题,我不知道为什么不能正常工作,我需要从数组中删除最小整数。

这是我的代码:

var players = [
    "Jug 1",
    "Jug 2",
    "Jug 3",
    "Jug 4"
];

var arrTotal = [72, 71, 70, 75];

function winners(arr) {
    var fstPlace = [], sndPlace= [];
    var min = Math.min.apply(null, arr);
    console.log(min);
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == min) {
            fstPlace.push(arr.indexOf(min, i));
        }
    }
    if (fstPlace.length == 1) {
        console.log("1st: " + fstPlace);
        arr.splice(min, 1);
        console.log(arr);
    }
    else {
        console.log("Tie: " + fstPlace);
    }
}

winners(arrTotal);

1 个答案:

答案 0 :(得分:1)

您必须提供要删除的项目的索引

var players = [
  "Jug 1",
  "Jug 2",
  "Jug 3",
  "Jug 4"
];

var arrTotal = [72, 71, 70, 75];

function winners(arr) {
  var fstPlace = [],
    sndPlace = [];
  var min = Math.min.apply(null, arr);
  snippet.log('min: ' + min);

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == min) {
      fstPlace.push(arr.indexOf(min, i));
    }
  }
  snippet.log('fstPlace: ' + fstPlace)
  if (fstPlace.length == 1) {
    snippet.log("1st: " + fstPlace);
    arr.splice(fstPlace[0], 1);
    snippet.log('result: ' + arr);
  } else {
    snippet.log("Tie: " + fstPlace);
  }
}

winners(arrTotal);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>