1. .each()]与.each()]与.each()]与().each()区别
$.each用于遍历数组、对象、数组对象, 代码形式(arr,function(index,value))或(obj, function(key, value) {})
().each用于遍历dom,代码形式如().each用于遍历dom, 代码形式如().each用于遍历dom,代码形式如(‘li’).each(function() { alert(this.xxx) })
demo:
<script>
$(function () {
// 对象
var a = { "name": 'Lucky', age: 12, sayName: function () { alert(this.name) } };
$.each(a, function (key, value) {
console.log(key + "===" + value);
});//name===Lucky age===12 sayName===function () { alert(this.name) }
// 数组
var b = ["Day", 2, 3];
$.each(b, function (f, e) {
console.log(f + ":" + e);
});//0:Day 1:2 2:3
// 对象数组
var c = [];
c.push(a);
$.each(c, function (index, value) {
console.log(index + "=" + value.name);
});//0=Lucky
// dom, 也可这么写function(index, e) {$(e).text()}
$('p').each(function () {
console.log($(this).text());
});
});
</script>
<p>如果您点击我,我会消失。</p>
<p>点击我,我会消失。</p>
<p>也要点击我哦。</p>
- for in 与 for of区别
for in能遍历数组与对象的可枚举属性,但是不仅遍历对象内部,而且会遍历原型链(若只遍历对象内部,配合obj.hasOwnProperty(【属性】))
for of,(ES6增加)能遍历数组,但是不能遍历对象(ES6遍历对象内部可用Symbol.iterator)
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]); //输出属性名称及属性值
}
for (ele in b) {
console.log(ele + ':' + b[ele]);//输出属性名称及属性值
}
for (ele of b) {
console.log(ele); //输出数组属性值
}
/*报错:VM3258 v.asp:19 Uncaught TypeError: a[Symbol.iterator] is not a function(…)*/
for (ele of a) {
console.log(ele +':' + a[ele]);
}