1. Difference between. each()] and. each()] and (). each()
$. each is used to traverse array, object, array object, code form (arr,function(index,value)) or (obj, function(key, value) {})
(). each is used to traverse dom. The code form is (). each is used to traverse dom. The code form is ('li '). each (function() {var XXX = this. XXX})
demo
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(function() {
// object
var a = {"name": 'Lucky', age: 12, sayName: function() { alert(this.name)}};
// array
var b = ["Day",2,3];
// object array
var c = [];
c.push(a);
$.each(b, function(index, value) {
console.log(index + ":" + value);
});
$.each(a, function(key, value) {
console.log(key + "==" + value);
});
$.each(c, function(index, e) {
console.log(index + "===" + e.name);
});
// dom, or function(index, e) {$(e).text()}
$('p').each(function() {
console.log($(this).text());
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click on me, I will disappear.</p>
<p>Click me, too.</p>
</body>
</html>
- Difference between for in and for of
for in can traverse the enumerable properties of arrays and objects, but it not only traverses the interior of objects, but also traverses the prototype chain (if it only traverses the interior of objects, cooperate with obj.hasOwnProperty([property]))
for of, (ES6 added) can traverse array, but not object (Symbol.iterator can be used inside ES6 traverse object)
demo
var a = {"name": 'Lucky', age: 12, sayName: function() { alert(this.name)}};
var b = ["Day",2,3];
var ele;
for (ele in a) {
console.log(ele +':' + a[ele]); //Output attribute name and value
}
for (ele in b) {
console.log(ele + ':' + b[ele]);//Output attribute name and value
}
for (ele of b) {
console.log(ele); //Output array property value
}
/*Error: VM3258 v.asp:19 Uncaught TypeError: a[Symbol.iterator] is not a function( )*/
for (ele of a) {
console.log(ele +':' + a[ele]);
}