【问题标题】:How to push the values in array based on position?如何根据位置推送数组中的值?
【发布时间】:2016-11-17 06:53:55
【问题描述】:

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

我的确切场景:

如果数组包含 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>

我的代码工作正常。但是有没有更好的解决方案只使用 Push 方法(不使用 pop)。

提前致谢。

【问题讨论】:

    标签: angularjs arrays push


    【解决方案1】:

    使用拼接方法。见fiddle

    fruits.splice(index, 0, item); 
    

    将项目插入到指定索引处的水果数组中

    【讨论】:

      【解决方案2】:

      你是在纯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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        相关资源
        最近更新 更多