js常用方法彙總
//Math.round()把數四捨五入為最接近的整數。
function random(m, n) {
return Math.round(Math.random() * (n - m)) + m;
}
console.log(random(20,30)) //20--30之間整數
```//splice() 方法向/從陣列中新增/刪除專案,然後返回被刪除的專案。
//arrayObject.splice(位置,專案數量,新專案)
//返回值:array(新陣列)
//ele.offsetHeight返回元素的高
function(ele,n){ //ele:Dom節點 n:分為多少塊
var num = new Array()
for (var i = 0; i < ele.offsetHeight / n - 1; i++) num.splice(i, 0, i);
return num
}
//$("barrage")元素的高是400 //分成20個小塊
console.log(block($("barrage"),20))//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
```
function $(id) {
return document.getElementById(id);
}
//console.log($("barrage")) //獲取id是barrage的dom元素
//其它分裝需要自己去探索
var arr = [1,2,3,4,5,6,7,8] function helfSearch(ary,num){ var len = ary.length, middle = Math.floor(len/2), mNum = ary[middle]; if(len === 0) return null else if(mNum === num) return middle; else if(mNum > num) return helfSearch(ary.slice(0,middle),num); else return helfSearch(ary.slice(middle+1),num); } //查詢某個元素在陣列中的位置 console.log('我是二分演算法') console.log(helfSearch(arr,1));
/**
* 判斷橫豎屏
* 橫屏 return 0
* 豎屏 return 1
*/
export let screen = () => {
let WB = document.documentElement.clientWidth,
HB = document.documentElement.clientHeight;
if (WB > HB) return 0;
else return 1;
}
//提交複選框中的資料 function getCheckboxVal(ele) { //獲取所有的複選框[ele:所有複選框的css選擇器] let check_ele = document.querySelectorAll(ele); let check_val = []; //存放複選框val的陣列 for (let k in check_ele) { //篩選出選中複選框的元素,向check_val中push val值 if (check_ele[k].checked) check_val.push(check_ele[k].value); } return check_val } console.log(getCheckboxVal(.imgbox input[type=checkbox]))
```["125","445","22","45","68","32","98"] ==> [125,445,22,45,68,32,98]
var arr = ["125","445","22","45","68","32","98"];
//使用map方法,也可以使用for迴圈
arr = arr.map(function(el){return parseInt(el);}); //[125,445,22,45,68,32,98]
<a name='數組合並去重排序'></a>
數組合並去重排序
let arr1 = [1, 25, 2, 26, 1234, 6, 213];
let arr2 = [2, 6, 2134, 6, 31, 623];
let c = [...new Set([...arr1, ...arr2])].sort((a, b) => {
return a - b;
});
<a name='原生操作class'></a>
原生操作class
//判斷有無
function hasClass(ele, cls) {
return ele.className.match(new RegExp("(\s|^)" + cls + "(\s|$)"));
}
//新增
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
//刪除
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
let reg = new RegExp("(\s|^)" + cls + "(\s|$)");
ele.className = ele.className.replace(reg, " ");
}
}
<a name='根據離開頁面來改變網頁title'></a>
根據離開頁面來改變網頁title
(function() {
var OriginTitile = document.title, titleTime;
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
document.title = '死鬼去哪裡了!';
clearTimeout(titleTime);
} else {
document.title = '(つェ⊂)咦!又好了!';
titleTime = setTimeout(function() {
document.title = OriginTitile;
},2000);
}
});
})();
```