js method encapsulation commonly used in development

1. Determine whether it is an array

 

function isArray(arr){
return Object.prototype.toString.call(arr) ==='[object Array]';
}
 
isArray([1,2,3]) //true

 

2. Judge whether it is a function (three kinds)

 
function isFunction(fn) {
return Object.prototype.toString.call(fn) ==='[object Function]';
return fn.constructor == Function;
return fn instanceof Function;
return typeof (fn) == Function;
}

 

3. Array de duplication, only considering that the elements in the array are numbers or strings

 

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. Dynamic de duplication

 

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 //Descending order
});
}
}
console.log(arr)//[1,2,3,4,5,6,7,8,9]
})
}
add()

  

5. Remove string spaces (three cases included)

 

function trim(str) {
return str.replace(/^[" "||" "]*/,"").replace(/[" "|" "]*$/,"");// Remove head and tail
return str.replace(/\s/g,'');//Remove all spaces
return str.replace(/(\s*$)/g,"");//Remove all spaces on the right
}

  

6. Determine whether it is email address

 

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. Determine whether it is a mobile phone number

 

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

  

8. Get the number of first elements in an object

 

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. Gets the position of the element relative to the browser window and returns a {x,y} object

 

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. Determine the number of times a letter appears in a string

 

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. Calculate the most frequent element in the array

 

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. Array filter (search function)

 

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 object (first)

 

//First kind
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;
};
//Second kinds
function clone(origin , target){
var target = target || {};
for(var propin origin){
target[prop] = origin[prop];
}
return target;
}

  

14. Deep clone

 

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'){//Judge prototype chain
target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {}//Determine whether the key of obj is an array
deepClone(origin[prop],target[prop]);//Recursive way
}else{
target[prop] = origin[prop];
}
}
}
return target

}

deepClone(obj,newObj);
console.log(newObj)

   

15. Finding the maximum and minimum value of an array

 

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 array de duplication

 

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. Compare two arrays and take out the intersection

 

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. Array and object comparison. The key of the object is the same as the array element

 

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. Delete an element in an array

 

//First kind
Array.prototype.remove = function(val){
var index = this.indexOf(val);
if(index !=0){
this.splice(index,1)
}
}
[1,3,4].remove(3)
//Second kinds
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. Determine whether an array contains an element

 

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

  

Keywords: Javascript Mobile JSON

Added by chomps on Tue, 24 Dec 2019 20:44:35 +0200