JavaScript 'in' operator for `undefined` elements in Arrays

前端 未结 3 862
谎友^
谎友^ 2020-11-27 06:40

Please consider the following snippet of code:

> a = [1, undefined, undefined, undefined, 3]
  [1, undefined, undefined, undefined, 3]
> b = [1,,,,3]
          


        
3条回答
  •  星月不相逢
    2020-11-27 07:20

    In your example, a[1] is defined, but is set to undefined, therefore 1 in a == true. By contrast, b[1] is not set at all, therefore 1 in b == false. This is why some people say that undefined is weird.

    To check whether an array a has the value 1, use a.indexOf(1) != -1.

    To check whether the a[1] is defined, use a.hasOwnProperty("1") (1 in a is subtly different, and is probably not actually what you want, because it can be true if 1 is defined in a's prototype but not in a itself).

    To set a[1] to undefined, use a[1] = undefined.

    To make a a[1] stop being defined, use delete a[1].

提交回复
热议问题