
1.2.2 history.replaceState
1.基本用法
history.replaceState的用法与history.pushState非常相似,区别在于history.replaceState将修改当前的历史记录项而不是新建一个。其语法为:

当需要更新当前栈指针所指向的栈记录,而不是增加历史栈时,可使用history.replaceState方法,该方法不会使history.length发生变化。

同history.pushState方法类似,history.replaceState方法也可传递state到历史栈的栈记录中。

对于state对象,history.replaceState同history.pushState一样使用结构化拷贝算法,如对象中不能设置函数:

2.历史栈变化
history.replaceState不会改变历史栈中记录的数量,如图1-3所示,当位于路径/b时,调用history.replaceState({a:3},null,'/c')方法会更新当前栈的信息,栈记录/b会被替换为/c,此时/b的记录会丢失,栈的记录数量不会发生变化。

图1-3 history.replaceState更新历史栈栈顶记录

如果当前的栈指针指向栈中间的记录,则此时调用history.replaceState方法,仅改变当前栈指针所指向的记录,如图1-4所示。

图1-4 history.replaceState更新非栈顶记录
/b的记录被替换为/c的记录,栈顶的/d记录不受影响,且栈指针依然位于中间位置。
history.replaceState与history.pushState的主要不同是,history.replaceState会替换当前指针位置的历史记录,并不会移动指针,也不会入栈新内容,history.length不会发生变化。