一、 看你了解es6+ 讲一下reduce的用法和场景?
reduce的参数有哪些?
大部分现代的数组方法都返回一个新的数组,而 Array.reduce() 更加灵活。它可以返回任意值,它的功能就是将一个数组的内容聚合成单个值。
这个值可以是数字、字符串,甚至可以是对象或新数组。
当时我回答的是用在累加方便比较多,累加时,初始值最好设置为0
arr.reduce(callback, [initialValue])
参数 callback里有四个值一般情况下写三个
当initialValue参数存在时,它就可以作为callback的第一个参数的初始值,并且遍历的次数从索引0开始,当initialValue参数不存在时,以数组的第一个元素作为callback第一个参数的初始值,并且遍历的索引从1开始;如果数据为空会报错,安全起见设置个初始值比较安全;
let arr = [1,2,3,4]; let arrresult = arr.reduce((accumulator, currentValue, currentIndex) => {
return accumulator+currentValue
},0)
console.log(arrresult) //10
此处参考的这个链接 链接:juejin.cn/post/689646…
二 、说一下this指向和改变this指向问题?
一、函数的调用方式决定了 this 的指向不同:
1.普通函数调用,此时this指向 window
function fn() {
console.log(this); // window
}
fn(); // window.fn(),此处默认省略window
2.构造函数调用,此时this指向 实例对象
function Person(age, name) {
this.age = age;
this.name = name
console.log(this) // 此处 this 分别指向 Person 的实例对象 p1 p2
}
var p1 = new Person(18, 'zs')
var p2 = new Person(18, 'ww')
3.对象方法调用,此时this指向 该方法所属的对象
var obj = {
fn: function () {
console.log(this); // obj
}
}
obj.fn();
4.通过事件绑定的方法,此时this指向 绑定事件的对象
<body>
<button id="btn">hh</button>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function() {
console.log(this); // btn
}
</script>
</body>
5.定时器函数,此时this指向 window
setInterval(function () {
console.log(this); // window
}, 1000);
二、更改this指向的三个方法
1.call() 方法 普通函数的this指向window,现在让我们更改this指向
var Person = {
name:"lixue",
age:21
}
function fn(x,y){
console.log(x+","+y);
console.log(this);
console.log(this.name);
console.log(this.age);
}
fn.call(Person,"hh",20); // this指向person
2.apply() 方法
Array.apply(thisArg,[argsArray])
apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表。 3.bind()方法 bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上
var oDiv1 = document.getElementById("div1");
oDiv1.onclick = function(){
setTimeout(function(){
console.log(this); // div1
}.bind(this),1000)
}
三、 怎样让已经点击的详情页回到原来点击的位置?
页面滚动,将滚动位置存到session中
// 滚动时 sessionStorage.setItem(key,value) 保存滚动位置
$(window).scroll(function(){
if($(document).scrollTop()!=0){
sessionStorage.setItem("offsetTop", $(window).scrollTop());//保存滚动位置
}
});
再次进到页面中,到session中取出上次保存的浏览位置,并滚动到对应位置
// onload时 sessionStorage.getItem(key) 取出并滚动到上次保存位置
window.onload = function()
{
var _offset = sessionStorage.getItem("offsetTop");
$(document).scrollTop(_offset);
};