# 电子表格实战锦囊:巧用稀疏数组是关键!

var arr = new Array(100)   //arr没有元素，但arr.length是100
var a = [];  //创建一个空数组，length为0
a[50] = 50;  //赋值添加一个元素，length为 51



JS中已经支持稀疏数组的存储，但在实际情况中，我们保存稀疏数组的保存并不是直接进行，而是会根据实际情况构建其他存储方式保存稀疏数组。想了解为什么要多此一举，这里就需要大家了解一个概念——数据持久化。

JSON.stringify(a)
'[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,50]'



JSON.parse(JSON.stringify(a))
(51) [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 50]



1、对象存储

{
"0": {
"0": {
"value": 0
}
},
"2": {
"1": {
"value": 2
},
"3": {
"value": "S"
}
},
"4": {
"3": {
"value": 3
}
}
}




function SparseArray(){
this._array = {}
}
SparseArray.prototype.setValue = function(row, col, data){
if(!this._array[row]){
this._array[row] = {}
}
this._array[row][col] = data
}
SparseArray.prototype.getValue = function(row, col){
if(this._array[row]){
return this._array[row][col]
}
return undefined;
}
let arr = new SparseArray();
arr.setValue(3, 3, 5);
console.log(arr.getValue(3, 3))    // 5


2、三元组

[
[1,1,1],
[5,8,2],
[4,3,3],
[1,5,4]
]


function TSMatrix(){
this._array = [];
this.undoStack = []
}

this._array.push([row, col, value])
}
TSMatrix.prototype.canUndo = function(){
return this._array.length > 0;
}
TSMatrix.prototype.undo = function(){
if(this._array.length > 0){
this.undoStack.push(this._array.pop())
}
}
TSMatrix.prototype.canRedo = function(){
return this.undoStack.length > 0;
}
TSMatrix.prototype.redo = function(){
if(this._array.length > 0){
this._array.push(this.undoStack.pop())
}
}
TSMatrix.prototype.print = function(){
console.log(JSON.stringify(this._array))
}

let mat = new TSMatrix();