JavaScript dot function

I am new to js, ​​so please be careful with me :)

I want to understand where we can use the point operator for some variable (in this case, an array), and when we cannot. consider the following code:

//example 1
function f1(x) {
    return x*x;
}
console.log(map(f1, [1,2,3,4,5]));
console.log([1,2,3,4,5].map(f1));

//example 2
function f2(arr) {
    return arr;
}
console.log(f2([1,2,3,4,5]));
console.log([1,2,3,4,5].f2());

I know that the examples are quite different, but still - in example 1, both printing works (and prints the same) - even when using the syntax array.function(..), while in example 2 the second print causes an error. basically, what is the difference between them and why does it work only in example 1?

and in general - can I apply this method to various types of variables (numbers, Booleans, etc.)?

+4
3

Array.prototype.map().

(. )

[1,2,3].map(function(x){ ... }): //In your case the callback function is *f1()*

arr.map(callback, [1,2,3]);

, Array , f2()

+3

[1,2,3,4,5] - "Array", "" map, :

[1,2,3,4,5].map(f1)

map , f1. map .

Array "class" f2, :

[1,2,3,4,5].f2()

f2 [1,2,3,4,5]

+1

In the first case, it mapis defined as a global function and a public function Array. Therefore, you can call it through map(arr)orarr.map(..)

In the second case, since you only defined f2 as a global function, which means that the array cannot access it.

0
source

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


All Articles