简体   繁体   English

使用array.splice()第一个参数未定义,仍然有效

[英]using array.splice() first parameter undefined, still works

I have an array that I am calling .splice() on. 我有一个要调用.splice()的数组。 By accident, sometimes the code runs with undefined as the first parameter eg. 偶然地,有时代码以undefined作为第一个参数运行,例如。

array.splice(undefined, 1);

but my code still works as though it was being called like: 但是我的代码仍然像被调用一样工作:

array.splice(0,1);

So my question is, why does this work? 所以我的问题是,为什么这行得通? Why does the following work? 为什么下面的工作?

[0, 1,2,3].splice(undefined,1); //returns 0

Thanks 谢谢

This occurs because Array.prototype.splice() treats falsey values the same as 0 , and undefined is falsey . 发生这种情况是因为Array.prototype.splice()falsey值视为与0相同,而undefinedfalsey

So you could also do: 因此,您也可以这样做:

[0, 1,2,3].splice(false,1); //returns 0
[0, 1,2,3].splice(null,1); //returns 0

Javascript developer are used to clean the value that you pass to the function in order to always have something to work with. JavaScript开发人员用于清除传递给函数的值,以便始终使用某些东西。

In this case, we can be sure that it's not an implicit coercion, because 在这种情况下,我们可以确定它不是隐式强制,因为

Number(undefined); //NaN
Number("text"); //NaN

While in splice function they are coerced to 0 . 拼接功能中,它们被强制为0

It's likely that they use a bitwise operator like >>0 他们可能会使用>> 0之类的按位运算符

"2">>0        //2
-8>>0         //-8
null>>0       //0
undefined>>0  //0
"text">>0     //0 

docs arr.slice([begin[, end]])如果undefined begin ,则slice从索引0开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM