Array.observe()

已废弃
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

Array.observe() 方法用于异步监视数组发生的变化,类似于针对对象的 Object.observe() 。当数组的值发生变化时,它按发生顺序提供了一个变化流。与 Object.observe() 类似,它由如下可接受的变化类型列表["add"、"update"、"delete"、"splice"]触发。

语法

Array.observe(arr, callback)

参数

arr
用于被监视的数组
callback
每当数组发生变化时,使用如下参数调用该函数:
changes
用于表示变化的对象数组。每个变化对象的属性如下:
  • name: 变化的属性名。
  • object: 变化后的数组。
  • type: 用于表示变化类型的字符串。其取值为"add"、"update"、"delete""splice"之一。
  • oldValue: 仅用于"update""delete"类型。变化之前的取值。
  • index: 仅用于"splice"类型。变化发生所在索引。
  • removed: 仅用于"splice"类型。被删除元素组成的数组。
  • addedCount: 仅用于"splice"类型。被添加的元素数量。

描述

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

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

示例

Example: Logging different change types

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'], addedCount: 3}]

标准规范

Strawman proposal specification.

浏览器支持

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
observe
Deprecated Non-standard
Chrome No support 36 — 52 Edge No support No Firefox No support No IE No support No Opera No support No Safari No support No WebView Android No support No Chrome Android No support No Firefox Android No support No Opera Android No support No Safari iOS No support No Samsung Internet Android No support No nodejs No support No

Legend

No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.

相关内容