splice(0) vs splice(0,undefined)

喜夏-厌秋 提交于 2020-01-11 12:29:07

问题


Splice with no second argument behaves as expected:

['a','b','c'].splice(0)            // Returns ['a','b','c']

But Splice with a undefined second argument behaves differently:

['a','b','c'].splice(0, undefined) // Returns []

Can someone explain to me the difference? I would expect the same (first) result.

It suggests that internally, splice is using "arguments.length" or similar, to change its behaviour, rather than checking the arguments.


回答1:


It suggests that internally, splice is using "arguments.length" or similar

Yes, that's exactly what happens internally.

If there is exactly one argument passed, it removes all elements until the end.
If there are more arguments passed, it takes the second one, casts it to an integer and uses it for the count of elements to be deleted. When you are passing undefined, it is cast to the number value NaN, which leads to the integer 0 - no elements are removed.




回答2:


According to docs, Array.prototype.splice returns deleted elements.

It also says that when second parameter deleteCount equals 0 then nothing is deleted.

So, in the first case you are deleting everything after index 0 inclusive and the result is whole array.

In the second case you are deleting 0 elements and the result is empty array.




回答3:


The reason the second result is empty is because, if the second parameter is 0 or negative, no elements are removed.

This is of course according to mozzila.




回答4:


Syntax is:

splice(index, delete, insert)

There is condition actually "if delete part assigning "false" values which are (undefined, 0, false) it will return empty array".

That is why in second syntax returning blank array"

['a','b','c'].splice(0) //returns complete array
['a','b','c'].splice(0, undefined) // Returns []


来源:https://stackoverflow.com/questions/48421239/splice0-vs-splice0-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!