fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[js] 第633天 以下方法调用call输出的结果是什么?请解释下?

Open haizhilin2013 opened this issue 4 years ago • 6 comments

第633天 以下方法调用call输出的结果是什么?请解释下?

作者:Minor5

3+1官网

我也要出题

[].copyWithin.call({ length: 5, 3: 1 }, 0, 3)

haizhilin2013 avatar Jan 07 '21 20:01 haizhilin2013

结果:{ 0: 1, 3: 1, length: 5 }

  1. 首先类数组转换为数组 [undefined, undefined, undefined, 1, undefined]

  2. 然后进行 copyWithin(0, 3) 操作得到 [1, undefined, undefined, 1, undefined]

  3. 最后恢复回类对象(忽略undefined,补上length) { 0: 1, 3: 1, length: 5 }

其实我的理解只算到第二步,不是很明白最后为什么会恢复为对象。

thainl avatar Jan 08 '21 05:01 thainl

结果:{ 0: 1, 3: 1, length: 5 }

  1. 首先类数组转换为数组 [undefined, undefined, undefined, 1, undefined]
  2. 然后进行 copyWithin(0, 3) 操作得到 [1, undefined, undefined, 1, undefined]
  3. 最后恢复回类对象(忽略undefined,补上length) { 0: 1, 3: 1, length: 5 }

其实我的理解只算到第二步,不是很明白最后为什么会恢复为对象。

类数组可以通过 call / apply 调用数组的几乎所有的原型方法。

你写的 1,2 两步可以很好地帮助理解代码的执行流程。

但是我认为程序执行时并没有做出类似的转换,应该只是操作了类数组对象的属性而已。因而会得到你上述的步骤 3 的结果。

数组也是对象,那么对数组或是类数组的操作的逻辑可以是类似的甚至是相同的。

以上只是我的想法,有大佬更清楚里面的细节的化,还请指教。

xujs0813 avatar Jan 08 '21 09:01 xujs0813

结果:{ 0: 1, 3: 1, length: 5 }

  1. 首先类数组转换为数组 [undefined, undefined, undefined, 1, undefined]
  2. 然后进行 copyWithin(0, 3) 操作得到 [1, undefined, undefined, 1, undefined]
  3. 最后恢复回类对象(忽略undefined,补上length) { 0: 1, 3: 1, length: 5 }

其实我的理解只算到第二步,不是很明白最后为什么会恢复为对象。

类数组可以通过 call / apply 调用数组的几乎所有的原型方法。

你写的 1,2 两步可以很好地帮助理解代码的执行流程。

但是我认为程序执行时并没有做出类似的转换,应该只是操作了类数组对象的属性而已。因而会得到你上述的步骤 3 的结果。

数组也是对象,那么对数组或是类数组的操作的逻辑可以是类似的甚至是相同的。

以上只是我的想法,有大佬更清楚里面的细节的化,还请指教。

一样的感觉,确实是对用数组的方法进行操作了,但在内部是没有进行转换,所以结果还是类数组。

C1oudust avatar Jan 08 '21 10:01 C1oudust

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin#polyfill

没有上面说的第一步, 因为没有发生数组转换 , 看polyfill实现就知道了

NoBey avatar Mar 13 '22 07:03 NoBey

数组的方法,对empty是不会执行的只会跳过。 这个地方数组方法会认为是 empty 而不是 undefined 因此该跳过的都跳过后,只有把 3位置的1 拷到0位置这一个动作。 而且不需要类型转换,只需要访问索引进行拷贝就行了,obj也能访问索引. 一个有lengtth属性的对象,都可以call数组的方法~ 完结~

chaoing avatar Feb 18 '24 09:02 chaoing

把长度为0的数组单独定义const arr = []再执行copyWithin,打印下console.log(arr),原数组没有发生变化。

seafronthu avatar Jun 12 '24 05:06 seafronthu