The Array. observe () method is used to asynchronously monitor changes in arrays, similar to Object. observe () for objects (). When the value of the array changes, it provides a change stream in the order of occurrence. Similar to Object. observe (), it is triggered by the following list of acceptable change types: [add, update, delete, and splice. The javascript Array. observe () method is used to asynchronously monitor changes in arrays.
Observe () syntax
Array.observe(arr, callback)
Observe () Parameters
Parameters |
Description |
Arr |
Array Used for monitoring |
Callback |
When the array changes, use the following parameter to call this function: changes Array of objects used to represent changes. The attributes of each change object are as follows:
name : Name of the changed attribute.
object : The changed array.
type : A variable type string.The value is "add ", "update"、 "delete" Or"splice" .
oldValue : Used only"update" And"Delete" type. Change The previous value.
index :Used only for the "splice" type. The index where the change occurs.
removed : Used only"Splice" type. An array composed of deleted elements.
addedCount : Used only"splice" Type. Number of added elements.
|
Observe () function
Every time the arr changes, the callback function is called. The called parameters are an array of all changes in the order of occurrence.
Note: The Array method is like Array. prototype. changes triggered by pop () will be reported as "splice" changes. Changes with unchanged length but index assignments will be reported as "update" changes.
Observe () instance:
var arr = ['a', 'b', 'c'];Array.observe(arr, function(changes) { console.log(changes);});arr[1] = 'B';// [{type: 'update', object: , name: '1', oldValue: 'b'}]arr[3] = 'd';// [{type: 'splice', object: , index: 3, removed: [], addedCount: 1}]arr.splice(1, 2, 'beta', 'gamma', 'delta');// [{type: 'splice', object: , index: 1, removed: ['B', 'c', 'd'], addedCount: 3}]
Array. observe () This feature is currently in the ECMAScript 7 Standard proposal
The current implementation may change or even be completely deleted in the future. Please use it with caution.