js之forEach和$.each

mac2024-03-30  32

forEach 在IE8不支持 ;['abc', 'd', 'efg'].forEach(function(item, index){ console.log(item); }); jQuery遍历 $.each(['abc', 'd', 'efg'], function (index, item) { console.log(item) })

这个each是jquery提供的 这个each在jQuery的原型链中

$('div').each(function(index, item){ console.log(item) });

each 方便的遍历jQuery元素 each 可以在不兼容forEach的低版本浏览器中使用jQuery的each方法

怎么把 jQuer对象转成document对象 ;[].slice.call($('div')).forEach(function(item){ console.log(item) })

slice方法的实现原理:

Array.prototype.mySlice = function () { var start = 0 var end = this.length if (arguments.length === 1) { start = argument[0] } else if (arguments.length === 2) { start = arguments[0] end = arguments[1] } var tmp = [] for (var i=start; i<end; i++) { tmp.push(this[i]) } return tmp } var fakeArr = { 0: 'abc', 1: 'efg', 2: 'haha', length: 3 } //这样就得到了真正的数组了 [].mySlice.call(fakeArr)
最新回复(0)