js知识碎片-历史管理

Math

Math 是一个内置对象, 它具有数学常数和函数的属性和方法。不是一个函数对象。(参考)

Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;

Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;

Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。

Math.random() 函数返回一个浮点, 伪随机数在范围[0,1),也就是说,从0(包括0)往上,但是不包括1(排除1),然后您可以缩放到所需的范围。
得到一个两数之间的随机数

1
2
3
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}

得到一个两数之间的随机整数

1
2
3
4
5
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

得到一个两数之间的随机整数,包括两个数在内

1
2
3
4
5
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}

window.location

window.location 只读属性,返回一个 Location 对象,其中包含有关文档当前位置的信息。(参考)

window.location.reload(true)
强制从服务器重新加载当前页面

window.location.hash
可以用来获取或设置页面的标签值

window.onhashchange

当 一个窗口的哈希改变时就会触发 hashchange 事件
语法:window.onhashchange = funcRef;或者:<body onhashchange="funcRef();">覆盖任何现有的事件处理程序。
为了将一个事件侦听器添加到现有的一个事件处理程序集中,使用函数 “addEventListener”。
window.addEventListener("hashchange", funcRef, false);

history

pushState: 三个参数: 数据 标题(没实现) 地址(可选)
popstate事件: 读取数据event.state
注意:网址是虚假的,需要在服务器指定对应页面,不然刷新找不到页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var obj = {};
$("#btn").click(function () {
var number = randomNumber(35, 7);
var oRD = Math.random(); //随机数作为obj的键值
obj[oRD] = number; // number 存入obj
$("div").text(number);
window.location.hash = oRD;
//history.pushState(number,'');
});
// window.onpopstate = function (ev) {
// var number = ev.state || '';
// $("div").text(number);
// }
/**
* 将hash插入div
*/
function hashNumber() {
var _number = location.hash;
$("div").text(obj[_number.substring(1)] || '');
}
window.addEventListener("hashchange", hashNumber,false);
/**
*
* @param total
* @param now
* @returns {Array}
*/
function randomNumber(total, now) {
var arr = [];
var newArr = [];
for (var i = 1; i<= total; i++) {
arr.push(i);
}
for (var i = 0; i<now; i++) {
newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1))
}
return newArr;
}

PJAX 介绍