Home  >  Article  >  Web Front-end  >  javascript Array.observe() 方法异步监视数组发生的变化

javascript Array.observe() 方法异步监视数组发生的变化

WBOY
WBOYOriginal
2016-06-01 09:54:272554browse

javascript Array.observe() 方法用于异步监视数组发生的变化。

observe()语法

<code class="language-javascript">Array.observe(arr, callback)</code>

 

observe()参数

参数 说明
arr 用于被监视的数组
callback

每当数组发生变化时,使用如下参数调用该函数:changes

用于表示变化的对象数组。每个变化对象的属性如下:

  • name: 变化的属性名。
  • object: 变化后的数组。
  • type: 用于表示变化类型的字符串。其取值为"add"、"update"、"delete"或 "splice"之一。
  • oldValue: 仅用于"update""delete"类型。变化之前的取值。
  • index仅用于"splice"类型。变化发生所在索引。
  • removed: 仅用于"splice"类型。被删除元素组成的数组。
  • addedCount: 仅用于"splice"类型。被添加的元素数量。

 

observe()功能

每次 arr 发生任何变化时,回调函数将被调用,调用参数为所有变化按发生顺序组成的数组。

注:通过Array方法如 Array.prototype.pop( ) 触发的变化将被报告成"splice"变化,长度不变但索引赋值发生变化的将被报告成"update"变化。

 

observe()实例:

<code class="language-javascript">var arr = ['a', 'b', 'c'];
Array.observe(arr, function(changes) {
  console.log(changes);
});

arr[1] = 'B';
// [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}]

arr[3] = 'd';
// [{type: 'splice', object: <arr>, index: 3, removed: [], addedCount: 1}]

arr.splice(1, 2, 'beta', 'gamma', 'delta');
// [{type: 'splice', object: <arr>, index: 1, removed: ['B', 'c', 'd'], addedCount: 3}]</arr></arr></arr></code>

 

Array.observe()该特性目前仍处于 ECMAScript 7 规范提案中

目前的实现在未来可能会发生改变,甚至被完全删除,请谨慎使用。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn