JavaScript performance (typeof arr [i] === "undefined" || num <arr [i])

I am looking for a way to avoid checking typeofon everyarr[i]

I need to consider the fact that arr[i]maybe0

I want to appoint arr[i] = numif arr[i]- undefinedor morenum

+4
source share
3 answers

A way to answer performance questions is to run tests.

There are four options:

  • arr[i] === undefined || num < arr[i]

  • typeof arr[i] === 'undefined' || num < arr[i]

  • !(i in arr) || num < arr[i]. This suggests that the values undefinedare true “holes” (missing indexes), not existing indexes, but they matter undefined.

  • !(num >= arr[i]). , undefined return false.

1 2 . 3 20 . 4 20% . isNaN, , 50% .

, , 1 2. , , 4. 4 , , , , undefined, .

. http://jsperf.com/ways-to-check-for-undefined/4.

+2

:

arr[i] == undefined || num < arr[i]

arr[i]=(arr[i] >= 0 && arr [i] < num) ? arr[i] : num;

arr[i]=(!isNaN(arr[i]) && arr [i] < num) ? arr[i] : num;
+1

something === something_else , , , , , :

typeof arr[i] === "undefined", num < arr[i], javascript .

, , typeof arr[i] === "undefined", num < arr[i] . >=, .

:

if (typeof arr[i] === "undefined" || num < arr[i])

:

if (!(num >= arr[i]))

...

  • , , , , . : ?

  • why do you even have undefined data in the list? Could you filter this out before writing to the list, and not while reading? It is a good idea to always have only one data type in the contaioner (unless you have a really good reason)

  • if you have a mapping of keys and values ​​with some undefined keys, perhaps Array is not a suitable container for your use.

+1
source

Source: https://habr.com/ru/post/1621667/


All Articles