2016-11-17 53 views
1

我正在推動數組中的值。如何根據位置推送數組中的值?

我的確切的情況:

如果數組包含2個值,按壓操作推入值具有後進來的2個值之間(這是基於位置)。

我以某種方式使用彈出最後一個值,並用popp值推送新值。以下是我的代碼。

var fruits = ["Banana", "Mango"]; 
 
document.getElementById("demo").innerHTML = fruits; 
 

 
function myFunction() { 
 
    var pop = fruits.pop(); 
 
    fruits.push("Kiwi",pop); 
 
    document.getElementById("demo").innerHTML = fruits; 
 
}
<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to add a new element to the array.</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<p id="demo"></p> 
 
    
 
</body> 
 
</html>

我的代碼是工作Fine.But是有隻使用Push方法的任何更好的解決方案(不使用POP)。

在此先感謝。

回答

2

對它使用拼接方法。見fiddle

fruits.splice(index, 0, item); 

將插入項目到水果數組的指定索引

1

你正在做它在純JavaScript的,在角

var app = angular.module('DemoApp', []) 
app.controller('DemoController', function($scope) { 
    var fruits = ["Banana", "Mango"]; 
    $scope.fruits = fruits; 
    $scope.myFunction = function() 
    { 
    $scope.fruits.push("Kiwi"); 
    } 
    console.log($scope.fruits); 
}); 

DEMO