多益网络
1.找出一个数组里面出现次数最多的元素并给其出现过的位置
使用reduce ES6
function findItemCount(arr){
let obj=arr.reduce((pre,cur)=>{
if(pre[cur]){
pre[cur]++
}else{
pre[cur]=1;
}
return pre
},{})
// 找到元素出现的次数最大数 可能有两个
let count = Math.max.apply([], Object.values(obj));
let address=[],res=[];
for (let key in obj){
count == obj[key] && address.push(key)
}
arr.reduce((pre, cur,index) => {
if(pre.includes(cur)){
res.push(index)
}
return pre
}, address)
console.log(address, res); //[ 'a', 'c' ] [ 1, 3, 4, 5, 6, 7 ]
}
findItemCount(array)
引申 求数组最大值的几种方法
var arr1 = [23, 42, 34, 234, 123, 12, 31, 23, 234, 34, 534, 534, 234, 23, 4];
console.log(Math.max(...arr1));
console.log(Math.max.apply([],arr1));
console.log(arr1.sort((a, b) => b - a)[0]);
const max=arr1.reduce((pre,cur)=>pre>cur?pre:cur)
console.log(max);
2.this指向,关于let声明其在window情况下,无法获取
let a=10;
let obj={
a:5,
say:function(){
console.log(this.a);
}
}
let func=obj.say;
let func2=obj.say.bind(obj);
func(); //undefined 第一次写成了10 忽略了let、var申明的区别
func2(); //5
let len = 10;
function fn() {
console.info(this.len) //undefined
}
fn();
let Person = {
len: 5,
say: function () {
fn(); //undefined
arguments[0](); //undefined 因为arguments对象调用fn方法,此时arguments对象里没有len属性,所以会报undefined;但有length属性,要注意把len改成length的情况
console.log(arguments[0] === arguments['0'], arguments.length, arguments); //true 1 [Arguments] { '0': [Function: fn] }
}
}
Person.say(fn);