常用javascript代码片段集锦

时间:2024-11-11 18:37:15

常用方法的封装

根据类名获取DOM元素

 var $$ = function (className, element) {
if (document.getElementsByClassName) {
return (element || document).getElementsByClassName(className);
}
var nodes = (element || document).getElementsByTagName('*'),
elements = [],
len = nodes.length,
i,
j,
currentNode,
classNames,
classLength;
for (i = 0; i < len; i++) {
currentNode = nodes[i];
classNames = currentNode.className.split(' ');
classLength = classNames.length;
for (j = 0 ; j < classLength; j++) {
if (classNames[j] === className) {
elements.push(currentNode);
break;
}
}
}
return elements;
}

判断是否是数字

 function isNum (numStr) {

     // 方法一:正则
// return /^\d+$/g.test(numStr); // 方法二:使用isNaN函数,可能存在潜在问题
return !isNaN(numStr);
}

从数组中删除指定下标的元素

声明一个临时数组,遍历原数组并判断是否等于给出的索引,如果相等则跳过本次循环;否则将其压入临时数组。

/**
* 从数组中删除指定下标的元素(返回的是新的数组并不影响原来的数组)
*/
 function deleteElement (index,arr) {

     var content = [];
for (var i = 0; i < arr.length; i++) {
if(index == i){
continue;
}
content.push(arr[i]);
}
return content;
}

常用效果案例

标题栏跑马灯

 // 标题栏实现跑马灯效果(可指定方向left,right)
var marqueeTitle = function(dir){ var title = document.title; var firstCh,leftChs,lastCh; // 第一个字符,剩下的字符和最后一个字符 if(dir == 'left'){
firstCh = title.charAt(0);
leftChs = title.substring(1,title.length);
document.title = leftChs + firstCh;
} else if(dir == 'right'){
lastCh = title.charAt(title.length - 1);
leftChs = title.substring(0,title.length - 1);
document.title = lastCh + leftChs;
} else {
console.error('跑马灯的方向只能是left和right');
return;
}
// console.log('当前文字的移动方向' + dir + ',' + document.title);
} window.onload = function(){
// 标题栏跑马灯(注意带参的函数应该使用引号)
setInterval('marqueeTitle("right")',500);
}

走动的页面时钟

 /**
* 当时钟数字不足2位数时补0
*/
function checkTime(i) {
return i < 10 ? '0' + i : i;
} /**
* 走动的页面时钟
*/
function timeDate(){ var now = new Date(), year = now.getFullYear(),
month = now.getMonth() + 1,
day = now.getDate(),
h = checkTime(now.getHours()),
m = checkTime(now.getMinutes()),
s = checkTime(now.getSeconds()),
weekday = '星期' + '日一二三四五六'.charAt(now.getDay()); getDOMById('time').innerHTML = year + "年" + month + "月" + day + "日 " + weekday + h + ":" + m + ":" + s; setTimeout(timeDate,1000);
} window.onload = function(){
timeDate();
}

抽签程序

 <button id="select">抽签</button>
<script>
/**
* 从数组中删除指定下标的元素(返回的是新的数组并不影响原来的数组)
*/
function deleteElement (index,arr) { var content = [];
for (var i = 0; i < arr.length; i++) {
if(index == i){
continue;
}
content.push(arr[i]);
}
return content;
} var data = [
{"no":1,"name":'张三'},
{"no":2,"name":'李四'},
{"no":3,"name":'王五'},
{"no":4,"name":'赵六'},
{"no":5,"name":'孙七'}
]; console.info(data);
var tmp = data;
document.getElementById('select').onclick = function (){
content = deleteElement(Math.floor(Math.random() * tmp.length),tmp);
tmp = content;
console.log(content); };
</script>

跳出$.each()遍历使用return false

 $.each(arr, function(index, val) {
console.log(index + '-->' + val);
if (index == 2) {
return false; // 只能是return false
};
});

Excel列编号转化为数字

 /**
* 将excel列转化为数字:A-->1,B-->2,AA-->27
*/
function convertColNumToInt(sHex) { const START = 'A'.charCodeAt(0) - 1;
const RADIX = 26;
var ret = 0;
for(let i = 0;i < sHex.length;i++){
ret *= RADIX;
ret += sHex.charCodeAt(i) - START;
}
return ret;
} // 法2
/**
* 将excel列转化为数字:A-->1,B-->2,AA-->27
*
* hash表存放
* A => 1,B => 2,...Z => 26
*/
function convertColNumToInt(sHex) { const RADIX = 26;
let m = new Map();
for(let i = 1;i <= 26;i++){
m.set(String.fromCodePoint(64+i),i);
} let ret = 0;
for(let i = 0;i < sHex.length;i++){
ret *= RADIX;
ret += m.get(sHex.charAt(i));
}
return ret;
}

判断2个数组是否相似

具体需求如下:

  • 数组中的成员类型相同,顺序可以不同。例如[1, true] 与 [false, 2]是相似的。

  • 数组的长度一致。

  • 类型的判断范围,需要区分:String, Boolean, Number, undefined, null, 函数,日期, window.

 function arraysSimilar(arr1, arr2) {

     if (!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length !== arr2.length) {
return false;
}
var t1 = [],
t2 = [];
// 依次取得2个数组中的元素类型并放入新的数组
for (var i = 0; i < arr1.length; i++) {
t1.push(typeOf(arr1[i]));
t2.push(typeOf(arr2[i]));
}
// 排序
t1.sort();
t2.sort();
// 比较排序后序列化的字符串
return t1.join() === t2.join();
} /**
* 得到元素的类型
*
* 单独判断null主要是兼容低版本IE
*/
function typeOf(element) {
return null === element ? "[object Null]" : Object.prototype.toString.call(element);
}

对象克隆

基本思路是逐个枚举属性,如果属性是对象,则进行递归处理。

 Object.prototype.clone = function() {
var newObj = {};
for(var i in this){
if(typeof(this[i]) == 'object' || typeof(this[i] == 'function')){
newObj[i] = this[i].clone();
} else {
newObj[i] = this[i];
}
}
return newObj;
} Array.prototype.clone = function() {
var newArr = [];
if(typeof(this[i]) == 'object' || typeof(this[i]) == 'function'){
newArr[i] = this[i].clone();
} else {
newArr[i] = this[i];
}
return newArr;
} Function.prototype.clone = function() {
var _this = this;
var newFunc = function () {
return _this.apply(this, arguments);
};
for(var i in this){
newFunc[i] = this[i];
}
return newFunc;
}

上面的代码在绝大多数情况下有效,但是当2个对象互相引用的时候就显得无力,会陷入死循环。必须使用图论算法建立拓扑关系,依次复制每个节点并重建依赖关系!

递归删除目录及文件

 // rmdir -r
var rmdir = function(dir) {
var list = fs.readdirSync(dir);
for (var i = 0; i < list.length; i++) {
var filename = path.join(dir, list[i]);
var stat = fs.statSync(filename);
if (filename === "." || filename === "..") {} else if (stat.isDirectory()) {
rmdir(filename);
} else {
fs.unlinkSync(filename);
}
}
fs.rmdirSync(dir);
};

复制项目模板文件到指定目录

 function copy(origin, target) {
if(!fs.existsSync(origin)) {
abort(origin + 'does not exist.');
}
if(!fs.existsSync(target)) {
mkdir(target);
console.log(' create : '.green + target);
}
fs.readdir(origin, function(err, datalist) {
if(err) {
abort(FILEREAD_ERROR);
}
for(var i = 0; i < datalist.length; i++) {
var oCurrent = path.resolve(origin, datalist[i]);
var tCurrent = path.resolve(target, datalist[i]);
if(fs.statSync(oCurrent).isFile()) {
fs.writeFileSync(tCurrent, fs.readFileSync(oCurrent, ''), '');
console.log(' create : '.green + tCurrent);
} else if(fs.statSync(oCurrent).isDirectory()) {
copy(oCurrent, tCurrent);
}
}
});
}

以上的程序常用于项目的初始化,例如express init默认生成了初始文件和项目。

判断节点是否包含另一个节点

 function contains(refNode, otherNode){
if (typeof refNode.contains == "function" && (!client.engine.webkit || client.engine.webkit >= 522)){
return refNode.contains(otherNode);
} else if (typeof refNode.compareDocumentPosition == "function"){
return !!(refNode.compareDocumentPosition(otherNode) & 16);
} else {
var node = otherNode.parentNode;
do {
if (node === refNode){
return true;
} else {
node = node.parentNode;
}
} while (node !== null);
return false;
}
}

页面失去焦点触发标题栏切换

 'use strict'

 let originTitile = document.title
let timer;
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
document.title = "(つェ⊂)赶快回来玩游戏啦"
clearTimeout(timer);
} else {
document.title = '(*´∇`*) 欢迎回来继续游戏 ' + originTitile
timer = setTimeout(function () {
document.title = OriginTitile
}, 3000)
}
})