欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

开发用到的js封装方法(20种)

程序员文章站 2022-05-25 22:22:40
1、判断是否是一个数组 function isarray(arr){ return object.prototype.tostring.call(arr) ==...

1、判断是否是一个数组

function isarray(arr){
return object.prototype.tostring.call(arr) ==='[object array]';
}
 
isarray([1,2,3]) //true

2、判断是否是一个函数(三种)

function isfunction(fn) {
return object.prototype.tostring.call(fn) ==='[object function]';
return fn.constructor == function;
return fn instanceof function;
return typeof (fn) == function;
}

3、数组去重,只考虑数组中元素为数字或者字符串

function newarr(arr){
var arrs = [];
for(var i =0;i<arr.length;i++){
if(arrs.indexof(arr[i])== -1){
arrs.push(arr[i])
}
}
return arrs;
}

4、动态去重

var arr = [1,2, 3, 4];
function add() {
var newarr = [];
$('.addele').click(() => {
var rnd = math.ceil(math.random() * 10);
newarr.push(rnd)
for (var i =0; i < newarr.length; i++) {
if (arr.indexof(newarr[i]) == -1) {
arr.push(newarr[i])
arr.sort(function (a, b) {
return b - a //降序
});
}
}
console.log(arr)//[1,2,3,4,5,6,7,8,9]
})
}
add()

5、去除字符串空格(包含三种情况)

function trim(str) {
return str.replace(/^[" "||" "]*/,"").replace(/[" "|" "]*$/,"");// 去除头和尾
return str.replace(/\s/g,'');//去除所有空格
return str.replace(/(\s*$)/g,"");//去除右边所有空格
}

6、判断是否为邮箱地址

function isemail(emailstr) {
var reg = /^[a-za-z0-9]+([._-]*[a-za-z0-9]*)*@[a-za-z0-9]+.[a-za-z0-9{2,5}$]/;
var result = reg.test(emailstr);
if (result) {
alert("ok");
} else {
alert("error");
}
}

7、判断是否是手机号

function ismobilephone(phone) {
var reg = /^1\d{10}$/;
if (reg.test(phone)) {
alert('ok');
} else {
alert('error');
}
}

8、获取一个对象里面第一次元素的数量

function getobjectlength(obj){
var i=0;
for( var attrin obj){
if(obj.hasownproperty(attr)){
i++;
}
}
console.log(i);
}
var obj = {name:'kob',age:20};
getobjectlength(obj) //2

9、获取元素相对于浏览器窗口的位置,返回一个{x,y}对象

function getposition(element) {
var offsety = 0;
offsety += element.offsettop;
var offsetx = 0;
offsetx += element.offsetleft;
if (element.offsetparent != null) {
getposition(element.offsetparent);
}
return { left: offsetx, top: offsety };
}

10、判断某个字母在字符串中出现的次数

var str = 'to be, or not to be, that is the question.';
var count = 0;
var pos = str.indexof('e');
while (pos !== -1) {
count++;
pos = str.indexof('e', pos + 1);
}
console.log(count) //4

11、计算出数组中出现次数最多的元素

var arrayobj = [1,1, 2, 3, 3, 3,4, 5, 5];
var tepm = '',count =0;
var newarr = new array();
for(var i=0;i<arrayobj.length;i++){
if (arrayobj[i] != -1) {
temp = arrayobj[i];
}
for(var j=0;j<arrayobj.length;j++){
if (temp == arrayobj[j]) {
count++;
arrayobj[j] = -1;
}
}
newarr.push(temp + ":" + count);
count = 0;
}
for(var i=0;i<newarr.length;i++){
  console.log(newarr[i]);
}

12、数组filter(搜索功能)

var fruits = ['apple','banana', 'grapes','mango', 'orange'];
function filteritems(query) {
return fruits.filter(function(el) {
return el.tolowercase().indexof(query.tolowercase()) > -1;
})
}
 
console.log(filteritems('ap')); // ['apple', 'grapes']

13、copy 对象(第一种)

//第一种
var cloneobj =function(obj) {
var newobj = {};
if (obj instanceof array) {
newobj = [];
}
for (var keyin obj) {
var val = obj[key];
newobj[key] = typeof val === 'object' ? cloneobj(val) : val;
}
return newobj;
};
//第二种
function clone(origin , target){
var target = target || {};
for(var propin origin){
target[prop] = origin[prop];
}
return target;
} 

14、深度克隆

var newobj ={};
function deepclone(origin,target){
var target = target || {},
tostr = object.prototype.tostring,
arrstr = "[object array]";
 
for(var propin origin){
if(origin.hasownproperty(prop)){
if(origin[prop] != "null" && typeof(origin[prop]) == 'object'){//判断原型链
target[prop] = (tostr.call(origin[prop]) == arrstr) ? [] : {}//判断obj的key是否是数组
deepclone(origin[prop],target[prop]);//递归的方式
}else{
target[prop] = origin[prop];
}
}
}
return target
 
}
 
deepclone(obj,newobj);
console.log(newobj)

15、求数组最大值和最小值

array.prototype.max = function(){
return math.max.apply({},this)
}
 
array.prototype.min = function(){
return math.min.apply({},this)
}
 
console.log([1,5,2].max())

16、json数组去重

function uniquepay(paylist){
var payarr = [paylist[0]];
for(var i =1; i < paylist.length; i++){
var payitem = paylist[i];
var repeat = false;
for (var j =0; j < payarr.length; j++) {
if (payitem.name == payarr[j].name) {
repeat = true;
break;
}
}
if (!repeat) {
payarr.push(payitem);
}
}
return payarr;
} 

17、对比两个数组,取出交集

array.intersect = function () {
var result = new array();
var obj = {};
for (var i =0; i < arguments.length; i++) {
for (var j =0; j < arguments[i].length; j++) {
var str = arguments[i][j];
if (!obj[str]) {
obj[str] = 1;
}
else {
obj[str]++;
if (obj[str] == arguments.length)
{
result.push(str);
}
}//end else
}//end for j
}//end for i
return result;
}
console.log(array.intersect(["1","2", "3"], ["2","3", "4", "5", "6"]))

18、数组和对象比较。取出对象的key和数组元素相同的

var arr = ['f00006','f00007','f00008'];
var obj = {'f00006':[{'id':21}],'f00007':[{'id':11}]}
var newobj = {};
for(var itemin obj){
if(arr.includes(item)){
newobj[item] = obj[item]
}
}
console.log(newobj)

19、删除数组中某个元素

//第一种
array.prototype.remove = function(val){
var index = this.indexof(val);
if(index !=0){
this.splice(index,1)
}
}
[1,3,4].remove(3)
//第二种
function remove(arr, indx) {
for (var i =0; i < arr.length; i++) {
var index = arr.indexof(arr[i]);
if (indx == index) {
arr.splice(index, 1)
}
}
return arr
}

20、判断数组是否包含某个元素

array.prototype.contains = function (val) {
for (var i =0; i < this.length; i++) {
if (this[i] == val) {
return true;
}
}
return false;
};
 
[1, 2,3, 4].contains(2)//true