简介
Map 是JavaScript中的数据结构,它允许存储【键,值】对,其中任何值都可以用作键或值;Map集合中的键和值可以是任何类型,并且如果使用集合中已存在的键将值添加到Map集合中,新值将替换旧值。
1.map()方法
返回一个新数组,数组中的元素为原始数组调用函数处理后的值,并且按照原始数组元素调用函数处理后的值
⚠️:map()不会对空数组进行检测,并且不会改变原数组
传参:currentValue:必传。当前元素值
index:可选。当前元素索引值
arr:可选。当前元素属于的数组对象
示例:数组中的每个元素乘以输入框指定的值,并返回新数组
var numbers = [65, 44, 12, 4];
function multiplyArrayElement(num) {
return num * document.getElementById("multiplyWith").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}
//获取输入框的值
let inp=document.querySelector("input")
inp.oninput=debounce(function(){
console.log(this.value)
},500)
2.节流
function throttle(fn,delay){
let canUse=true
return function(){
if(canUse){
fn.call(this)
canUse=false
setTimeout(()=>{canUse=true},delay)
}
}
}
//滚动条触发
window.onscroll=throttle(function(){
console.log("滚动了")
},500)