Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS not set variable after loop

I can`t get why in my function not changing value of variable. Here my code.

var count = function(datain){
  let temparr = [],
  countobj = {};

  $.each(datain, function(key, val) {
    console.log(temparr);
    countobj.cost = +$(val).find("[name]").text();
    console.log(countobj);
    temparr.push(countobj);
    console.log(temparr);
  });

  console.log(temparr);
  return temparr;
};

let countarr = count(datain);
console.log(countarr);

This function part of function that fires on ajax success, ajax i call on some select changes. Datain - result of ajax. At first time call this function work`s fine, but all another fires returns me first time set countarr. All data in key, val - correct, but i cant understand why "countarr" returns me result of first call and not re-set temparr inside function. Thanks for reply!

like image 335
Doom Avatar asked Sep 05 '16 06:09

Doom


People also ask

Do JavaScript variables declare outside or inside loop?

JavaScript variables declare outside or inside loop? The ECMA-/Javascript language hoists any variable which is declared with var anywhere to the top of a function. That is because this language does have function scope and does not have block scope like many other C-like languages.

How does the for loop work in JavaScript?

For example, processing a response after an HTTP request is completed or after some other processing is done. So what happens then, is that the doSthWithCallbacks (general expression for all JavaScript function that use a callback) schedules the callback function to be executed at a later stage. But the for loop isn't just scheduling one callback.

Is it wise to declare variables within a loop?

I thought it wasn't wise to declare variables within a loop. It's not. Another unwise thing is reassigning a const. Show activity on this post.

How to create a variable in JavaScript with no value?

var answer = 'Yes I am!'; Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword: After the declaration, the variable has no value (technically it has the value of undefined ). To assign a value to the variable, use the equal sign:


1 Answers

You're reusing the same countobj object on each loop, pushing a reference to that single object repeatedly into the array.

You need to create a new object on each loop:

var count = function(datain) {
    let temparr = [],
        countobj;                                          // ***
    $.each(datain, function(key, val) {
        countobj = {};                                     // ***
        console.log(temparr);
        countobj.cost = +$(val).find("[name]").text();
        console.log(countobj);
        temparr.push(countobj);
        console.log(temparr);
    });
    console.log(temparr);
    return temparr;
};
let countarr = count(datain);
console.log(countarr);

As there's just the one property, you don't need a variable. Here's that same code without the variable and with the console.log lines removed:

var count = function(datain) {
    let temparr = [];
    $.each(datain, function(key, val) {
        temparr.push({cost: +$(val).find("[name]").text()});
    });
    return temparr;
};
let countarr = count(datain);
console.log(countarr);

Or you could even use map; and since you're using ES2015+ (I can tell from let), we can use an arrow function:

let count = function(datain) {
    return datain.map(val => ({cost: +$(val).find("[name]").text()}));
};
let countarr = count(datain);
console.log(countarr);

If datain is only array-like, not an actual array, use Array.from instead of map:

let count = function(datain) {
    return Array.from(datain, val => ({cost: +$(val).find("[name]").text()}));
};
let countarr = count(datain);
console.log(countarr);
like image 173
T.J. Crowder Avatar answered Oct 31 '22 19:10

T.J. Crowder