S
S
shpeks2019-12-10 18:28:44
JavaScript
shpeks, 2019-12-10 18:28:44

How to extract the value from an anonymous function to a global variable?

There is an anonymous function, you need to pull out a variable from it for further use

let np;

window.onclick = function(e){
  var elem = e ? e.target : window.event.srcElement;
  np = elem.id + "";
  alert(np);
  return np;
};

console.log(np);

The function takes the id of the selected html element and sends it to elem.id, the alert prints everything correctly, but outputs undefined to the console. Please tell me how to fix? so that the same id is entered into the np variable.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
L
Lander, 2019-01-14
@sergius-mary

The construction for (oneNumber in myNumbers)actually means the following:
Go through all the keys of the array in turn myNumbersand at each step put the value of the key into the variable oneNumber. After that, the addition occurs myNumbers[oneNumber], that is, the values ​​in the array myNumbersby index oneNumber, to the variable total.

M
Maks Kovyvchak, 2019-01-14
@max_front

in other words
, here is the equivalent entry to your
for loop (var oneNumber in myNumbers) {
total = total + myNumbers[oneNumber];
}
In each iteration of the loop, the oneNumber variable is created and the element from the myNumbers array is written there

S
Sergey Sokolov, 2019-01-14
@sergiks

oneNumberforgot to announce.
You should add a line abovevar oneNumber;

A
Andrey Okhotnikov, 2019-01-14
@tsepen

Read about the for in construction https://developer.mozilla.org/ru/docs/Web/JavaScri...
In this case, oneNumber is the index of an element in an array, it can be called anything, even i, even value , even oneNumber.
The for in loop iterates through all the elements of the array in turn, takes the corresponding element and adds to the total variable. As soon as all elements are enumerated, the following function will work - document.write (total);

W
WinPooh32, 2019-12-10
@shpeks

Equivalent code:

let np;
 
function callback(e){
  var elem = e ? e.target : window.event.srcElement;
  np = elem.id + "";
  alert(np);
  return np;
};

window.onclick = callback;
console.log(np);

So it is clearer why your code does not work as you intended?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question