0: 1,
length: 1
}
Array.prototype.push.call(arrlike, 1) // {0: 1, 1: 2, length: 2}
apply
求数组的最大值与最小值
JavaScript中没有给数组提供类似max和min函数,只提供了Math.max/min
,用于求多个数的最值,所以可以借助apply方法,直接传递数组给Math.max/min
const arr = [1,10,11,33,4,52,17]
Math.max.apply(Math, arr)
Math.min.apply(Math, arr)
初步模拟
首先看一个简单例子,分析一下call
函数执行过程:
var obj = {
value: 1
}
function fun() {
console.log(this.value)
}
fun.call(obj) // 1
可见call
函数调用大致执行了两部:
-
call
改变了this
指向,this->obj
-
fun
函数执行
那该如何模拟上面的效果那?如果在obj上定义函数fun,之后obj.fun执行是不是就达成了上述的效果。
所以call
的模拟步骤大约是:
-
将函数
fn
设为thisArg
的对象的方法 -
执行
thisArg.fn
-
删除该函数
Function.prototype.myCall = function (thisArg) {
// this为调用myCall的函数
thisArg.func = this;
thisArg.func();
delete(thisArg.func);
}
完善
上面实现了call
的最初版代码,还有几个地方有待解决:
- 未传入
thisArg
参数:当未传入thisArg
或传入null
时,函数的this->window
thisArg = thisArg || window
- 传入
arg1,arg2
等参数:ES6可以通过rest
参数来实现,ES6以前可以通过arguments
来实现
// ES5
const args = []
for (let i = 1; i<arguments.length; i++) {
args.push(‘argumens[’+ i + ‘]’)
}
eval(‘thisArg.func(’ + args +‘)’)
eval()
函数计算JavaScript
字符串,并把它作为脚本代码来执行。
array
在与字符串相加时,会调用array.toString
方法([1,2,3].toString() // "1,2,3"
)。
- 函数可以拥有返回值
举个例子:
const obj = {
value: 1
}
function func(name, age) {
return {
name,
age,
value: this.value
}
}
func.call(obj, ‘zcxiaobao’, 24)
// {
// age: 24,
// name: “zcxiaobao”,
// value: 1,
// }
不过很好解决,因此只需将eval执行之后的结果返回即可。
接着我们来看一下完整版的代码:
Function.prototype.myCall = function (thisArg) {
thisArg = thisArg || window;
thisArg.func = this;
const args = []
for (let i = 1; i<arguments.length; i++) {
args.push(‘arguments[’+ i + ‘]’)
}
const result = eval(‘thisArg.func(’ + args +‘)’)
delete thisArg.func;
return result;
}
如果使用ES6语法进行模拟代码会简单很多
Function.prototype.myCall = function (thisArg, …args) {
thisArg = thisArg || window;
thisArg.func = this;
args = args || []
const result = thisArg.func(…args)
delete thisArg.func;
return result;
}
apply
的代码实现与call
类似,这里直接给代码。
Function.prototype.myApply = function (thisArg, arr) {
thisArg = thisArg || window;
thisArg.func = this;
const args = []
for (let i = 0; i<arr.length; i++) {
args.push(‘arr[’+ i + ‘]’)
}
const result = eval(‘thisArg.func(’ + args +‘)’)
跳槽是每个人的职业生涯中都要经历的过程,不论你是搜索到的这篇文章还是无意中浏览到的这篇文章,希望你没有白白浪费停留在这里的时间,能给你接下来或者以后的笔试面试带来一些帮助。
也许是互联网未来10年中最好的一年。WINTER IS COMING。但是如果你不真正的自己去尝试尝试,你永远不知道市面上的行情如何。这次找工作下来,我自身感觉市场并没有那么可怕,也拿到了几个大厂的offer。在此进行一个总结,给自己,也希望能帮助到需要的同学。
面试准备
面试准备根据每个人掌握的知识不同,准备的时间也不一样。现在对于前端岗位,以前也许不是很重视算法这块,但是现在很多公司也都会考。建议大家平时有空的时候多刷刷leetcode。算法的准备时间比较长,是一个长期的过程。需要在掌握了大部分前端基础知识的情况下,再有针对性的去复习算法。面试的时候算法能做出来肯定加分,但做不出来也不会一票否决,面试官也会给你提供一些思路。