Jquery has an each method to simplify the loop. Es then uses a forEach method, which is similar in usage but does not handle object types. The continue effect cannot be achieved by returning true. There is also the every method, which does continue but is completely useless when dealing with class arrays and object types.
How to handle each without using jquery; Or how to do it with native? A library, jTool, was written earlier to implement this method.
Simple implementation:
// the function each is implemented literally
var each = function(object, callback){
var type = (function(){
switch (object.constructor){
case Object:
return 'Object';
break;
case Array:
return 'Array';
break;
case NodeList:
return 'NodeList';
break;
default:
return 'null';
break;
}
})();
// If it is an array or a class array, return: index, value
if(type === 'Array' || type === 'NodeList') {// The every method cannot be called directly because the class array NodeList exists
[].every.call(object, function(v, i){
return callback.call(v, i, v) === false ? false : true;
});
}
// Return key, value in object format
else if(type === 'Object') {for(var i in object){
if(callback.call(object[i], i, object[i]) === false) {break; }}}}Copy the code
Let’s try arrays, objects, class array types, and interrupt effects
An array type
var _array = [1.2.3.4];
each(_array, function(i, v){
console.log(i + ':' + v);
});
Copy the code
The output is as follows:
Object type
var object = {a:1, b:2, c:3} each(object, function(i, v){ console.log(i + ‘: ‘ + v); }); The output is as follows:
Class array type
var ele = document.querySelectorAll('div');
each(ele, function(i, v){
console.log(i + ':' + v);
});
Copy the code
The output is as follows:
Add interrupt condition
var object2 = {name:'baukh'.age: 'and'.six:'male'.url: 'www.lovejavascript.com',}
each(object2, function(i, v){
if(i === 'age') {// If there is an age attribute, print a warning for the continue effect
console.log('Exists with key age, this guy has already'+v+'old');
return true;
}
if(i === 'six' && v === 'male') {// If there is an age attribute, the output pops out to achieve the break effect
console.log('select * from' six 'where key =' male ');
return false;
}
console.log(i + ':' + v);
});
Copy the code
The output is as follows:
As you can see from the results, the each method already implements the each functionality of jquery. And the implementation is so simple ~
It was the best of times for the front-end, it was the worst of times for the front-end. There are so many front-end frameworks flying around, and as jQuery’s role in the front-end industry slowly weakens, there is always a sense of loss and comfort. Good luck to each other, gentlemen.
Another table component, gridManager, is recommended