如何根据位置推送数组中的值?

How to push the values in array based on position?

我正在努力推动数组中的值。

我的具体情况:

如果数组包含 2 个值,在推送操作之后,推送的值必须介于 2 个值之间(基于位置)。

我以某种方式使用弹出最后一个值并使用弹出值推送新值来做到这一点。下面是我的代码。

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)是否有更好的解决方案。

提前致谢。

使用拼接法。见 fiddle

fruits.splice(index, 0, item); 

将在指定索引处将项目插入 fruits 数组

你是在纯粹的javascript,在angular

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