every案例
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" >
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Document</title>
</head>
<body>
<label for="" >全选</label>
<input type="checkbox" id="all" />
<div>
<input type="checkbox" class="box" />
<input type="checkbox" class="box" />
<input type="checkbox" class="box" />
<input type="checkbox" class="box" />
<input type="checkbox" class="box" />
<input type="checkbox" class="box" />
</div>
<script>
var all = document.getElementById ( 'all' ) ;
var box = document.getElementsByClassName ( 'box' ) ;
box=Array.from ( box) ;
all.onclick = function () {
// box.forEach is not a function
// 第一种:函数名写错
// 第二种:这个box没有这个方法
// 伪数组不可以使用数组的方法
// 把伪数组转化为真数组的方法
box.forEach(function (item, index) {
// console.log ( item) ;
item.checked=all.checked;
} )
} ;
// 循环给复选框绑定点击事件
box.forEach(function(item) {
item.οnclick=function() {
// 判断所有的复选框是否被选上
// 如果所有的复选框被选上 all。checked=true
// 如果有其中一个没有被选上 all.checked=false
var res= box.every(function(data) {
return data.checked==true;
} )
all.checked=res;
}
} )
</script>
</body>
</html>
伪数组转化为真数组的方法
ES5的方法:Array.prototype.slice.call(元素对象) ES6的方法:Array.from(元素对象)
reduce去重
var arr = [1, 1, 2, 2, 12, 34, 3, 3, 4, 5, 6, 4, 3, 5];
// 给一个新数组,判断新数组中是否存在这个数据,如果不存在就把这个数据添加到新数组中
var res = arr.reduce(function (pre, item) {
// console.log ( pre) ;
// 把pre当成新数组,pre的默认值为空数组
if (pre.indexOf(item) == -1) {
// pre数组中不存在 item这个数据,就需要把item添加到 pre中
// push ( ) 方法值是一个数组的长度(数字),相当于 下一次的循环 pre的值为一个数字,pre.indexOf ( ) 报错
// return pre.push ( item) ;
// concat ( ) 函数的返回值为数组
return pre.concat ( item) ;
}
return pre;
} , []) ;
console.log ( res) ;
计算两个数的交集
var nums1 = [1, 2, 2, 3, 5],
nums2 = [2, 3, 4, 5, 6];
// 过滤filter来实现
// 链式调用(函数的高阶应用)
var res = nums1
.filter(function (item) {
return nums2.indexOf ( item) != -1;
} )
.reduce(function (pre, item) {
if (pre.indexOf(item) == -1) {
return pre.concat ( item) ;
}
return pre;
} , []) ;
// console.log ( res) ;
找到数组中消失的数据
var arr = [4, 3, 2, 7, 8, 2, 3, 1];
var newArr = [];
// 找到数组中最大值和最小值
var max = arr.sort(function (a, b) {
return b - a;
} ) [0];
var min = arr[arr.length - 1];
for ( var i = min; i <= max; i++) {
if (arr.indexOf(i) == -1) {
newArr.push ( i) ;
}
}
console.log ( newArr) ;
找到数组中数据中出现的次数
var arr = [1, 2, 3, 1, 1, 1, 2, 2, 3, 3, 4];
// 对象的属性是唯一
// 循环数组,把数组中的数据当成对象属性,出现的次数当成对象属性值
var obj = { } ;
arr.forEach(function (item) {
// 判断对象中是否存在某个属性
if (obj[item]) {
obj[item] = ++obj[item];
} else {
obj[item] = 1;
}
// obj.item==> { item : }
// item =1 obj[item]===> { 1: }
} ) ;
for (var key in obj) {
console.log ( key + "出现的次数为" + obj[key]) ;
}