2015-08-21 115 views
1

我在我的代碼中有splice問題,我不知道爲什麼不工作,我需要從數組中刪除最小整數。拼接不從數組中刪除項目javascript

這裏是我的代碼:

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

你必須給該項目的索引中刪除

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>

+0

我不能使用本身的價值? – Devsalad

+0

謝謝Arun,它完美的作品。我必須等待6分鐘才能接受答案。 :) – Devsalad