Array.slice on array with one element

我与影子孤独终老i 提交于 2020-01-03 17:45:07

问题


I'm really confused by this. If I do something like this:
[1].slice(1)
it returns an empty array (in the chrome interactive console). But if I compare:
[1].slice(1) === []
it's always false. So my Question is, what does [1].slice(1) really return?


回答1:


=== compares objects by references.
You're comparing two different array objects which are both empty.

If you want to check whether an array is empty, check whether .length === 0.




回答2:


That's not a problem of slice or ===.

If you do [1]==[1], it returns false.

That's because both == and === compare objects by reference




回答3:


[] === [] also returns false. [1].slice(1) does in fact return []




回答4:


You better check the length:

[1].slice(1).length; // falsey


来源:https://stackoverflow.com/questions/11938712/array-slice-on-array-with-one-element

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