替换数组内容的简单方法 [英] Short way to replace content of an array

查看:36
本文介绍了替换数组内容的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方便的方法来替换数组的内容,并保留对它的引用?我不想像这样替换数组:

Is there any convenient way to replace the content of an array, AND keep a reference to it? I don't want to replace the array like this:

var arr1 = [1,2,3];
var referenceToArr1 = arr1;
var arr2 = [4,5,6];

arr1 = arr2;
// logs: [4,5,6] false
console.log(arr1, arr1===referenceToArr1);
// logs [1,2,3]
console.log(referenceToArr1);

这种方式arr1arr2的内容,但是我在referenceToArr1中丢失了引用,因为它仍然指向原文 arr1.

This way arr1 has the content of arr2, but I loose the reference in referenceToArr1, because it still points to the original arr1.

通过这种方式,我不会丢失引用:

With this way, I don't loose the reference:

var arr1 = [1,2,3];
var referenceToArr1 = arr1;
var arr2 = [4,5,6];

arr1.length = 0;
for (var i = 0; i < arr2.length; i++) {
  arr1.push(arr2[i]);
}
// logs: [4,5,6] true
console.log(arr1, arr1===referenceToArr1);
// logs: [4,5,6]
console.log(referenceToArr1)

这里的缺点是,我必须清空 arr1.length = 0,遍历 arr2 的每个元素并将其推送到 arr1> 手动.

The drawback here is, that I have to empty arr1.length = 0, iterate over every element of arr2 and push it to arr1 by hand.

我的问题是:

  • 当然,我可以为此编写一个帮助程序,但最有效的方法是什么?
  • 是否有一种简短的、原生的 javascript 方法来执行此操作(也许是单行?)
  • 我也在使用 underscore.js,但还没有找到解决此类问题的方法.有没有办法用 underscore.js 做到这一点?

背景:

我有一个带有服务的 AngularJS 应用程序.在这个服务中,我有一个数组来保存从服务器加载的所有元素.来自服务 get 的数据绑定到控制器并在视图中使用.当来自服务的数据发生变化时(例如发生重新获取),我想自动更新我的控制器变量和它绑定到的视图.

I have an AngularJS app with a service. Inside this service, I have an array to keep all the elements loaded from the server. The data from the service get's bind to a controller and is used in a view. When the data from the service get's change (e.g. a refetch happens), I want to auto update my controllers vars and the view it is bind to.

这是一个 Plunker:http://plnkr.co/edit/8yYahwDO6pAuwl6lcpAS?p=预览

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, myService) {
  $scope.name = 'World';
  myService.fetchData().then(function(data) {
    console.log(data)
    $scope.data = data;
  })
});

app.service('myService', function($timeout, $q) {
  var arr;
  var deferred;

  var loadData = function() {
    // here comes some data from the server
    var serverData = [1,2,3];
    arr = serverData;
    deferred.resolve(arr);

    // simulate a refetch of the data
    $timeout(function() {
      var newServerData = [4,5,6];
      // this won't work, because MainCtrl looses it's reference
      // arr = newServerData;
    }, 1000);

    $timeout(function() {
      var newServerData = [7,8,9];
      arr.length = 0;
      [].push.apply(arr, newServerData);
    }, 2000);

    $timeout(function() {
      var newServerData = [10,11,12];
      [].splice.apply(arr, [0, arr.length].concat(newServerData));
    }, 3000);
  }

  return {
    fetchData: function() {
      deferred = $q.defer();

      loadData();

      return deferred.promise;
    }
  }
})

和视图:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="d in data">{{d}}</li>
    </ul>
    3 refetches every second
  </body>

</html>

推荐答案

这个怎么样:

// 1. reset the array while keeping its reference
arr1.length = 0;
// 2. fill the first array with items from the second
[].push.apply(arr1, arr2);

见:

  1. 如何在 JavaScript 中清空数组?
  2. .push() 将多个对象放入 JavaScript 数组返回未定义"

这篇关于替换数组内容的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆