global list empty when called in another function - javascript

I have defined a global list. I have a function that pushes values onto that list, this one works fine. However, I have another function, called after the function pushing the values is done, that needs the values from this list. Unfortunately, when I call the list in this last function, it shows as empty. Why is that?
simplified JS:
var recherche=[];
function clickUpdates() {
switch(count) {
// call recherche.push() multiple times
}
function lancement_scraping() {
console.log(recherche); //shows recherche as empty array
//window.close()
}

Related

Confusion with the use of higher order function in JS

I am new to JS and was learning how to create and use higher order functions in JS. I faced a bit of confusion with this code:
function elListMap(transform, list) {
// list might be a NodeList, which doesn't have .map(), so we convert
// it to an array.
return [...list].map(transform);
}
function addSpinnerClass(el) {
el.classList.add('spinner');
return el;
}
// Find all the buttons with class 'loader'
const loadButtons = document.querySelectorAll('button.loader');
// Add the spinner class to all the buttons we found.
elListMap(addSpinnerClass, loadButtons);
The question is Why don't we pass argument to addSpinnerClass when addSpinnerClass itself is passed to elListMap. I mean shouldn't we have elListMap(addSpinnerClass(loadButtons), loadButtons); instead of elListMap(addSpinnerClass, loadButtons);
loadButtons is a list of elements. If you passed it to addSpinnerClass it would try to call the classList.add() method of that list of elements.
Since it is a list of elements and not an element, this would error and the program would stop.
If it didn't error, then you would pass the return value of addSpinnerClass (the value you passed into it: i.e. the list) as the first argument to elListMap.
elListMap would then pass that as the first argument to map. The first argument to map needs to be a function, but you would be passing a list of elements. So, again, it would error.

chrome.storage.local.get an object and iterating through obj keys

I'm having trouble using the chrome.storage.local.get feature. I have all working, except I don't understand how to handle the .get function.
I want to copy an object by clicking a button, from one chrome tab to another one. I have a loop to get my Object keys, and I can save it successfuly in chrome local storage by:
chrome.storage.local.set({
'copiedObj': obj
});
but, when trying to use the .get function, I can't specify the key number I want. I need the key number because the keys and their values changes every time because i'm copying data from different pages.
$('#targetInfo').click(function(){
console.log('context 2 received');
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
});
this gets me the full object keys and values, but when trying to change it to get the first key (changing the console.log inside the script to items[0], I get an undefined error message in the console.
I want it to iterate through all the keys, and assign key to a variable, value to a variable and execute a function. For each key by it's time. I've written a detailed explanation inside the code:
//Get the DOM input field
var specific_name = document.getElementById('new_specific_name');
var specific_value = document.getElementById('new_specific_value');
//Start loop, from 0 to the last object keys
for (i=0;i<items.length;i++) {
//Set specific_name value to the first key inside the object
specific_name.value = XXX[i];
//Set specific_value value to the matching key value inside the object
specific_value.value = ZZZ[i];
//Execute this function
add_new_specific();
}
(minimal solution, pending clarification) As mentioned before,
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
should be
var storage = chrome.storage.local.get('copiedObj', function (result) {
console.log(result.items);
console.log(result.items[0]); // if items is an array...
});
To loop through an object, see https://stackoverflow.com/a/18202926/1587329. You need to do this all inside the anonymous function in .get.

How to store multiple items on Local Storage when a button is clicked?

I'm trying to store multiple items based on this function:
onclick="s(iId)"
This is the function that I'm using:
function s(i_id) {
var items = [];
items.push(i_id);
localStorage.setItem("i", JSON.stringify(i));
}
The problem is that it is only storing one id when the button is clicked and refreshed every time is clicked. How can I make it store multiple ids?
The problem is, you're creating a new array, pushing a single id in it, and then saving it every time the function is called. Two things you could do is move the items array outside of the function, and simply push to it, before saving them. The second option is, getting the already stored value, parsing it with JSON.parse and pushing a new item in it, before saving it again.
I suggest going with option 1, even if it creates a global variable. It's much faster.
var items = [];
function store(item_id) {
items.push(item_id);
localStorage.setItem("item", JSON.stringify(items));
}
You have to call the onclick like this:
onclick="store([itemId1, itemId2, itemId3])"
and the function:
function store(item_ids) {
var items = [];
for(var i = 0; i < item_ids.length; i++) {
items.push(item_ids[i]);
}
localStorage.setItem("item", JSON.stringify(items));
}
Considering if you want to add new array to storage on every click...

React.js onClick in recursive function

I'm doing a hierarchy tree view in React.js by recursion. I fetch categories from the DB and prepare an array in a structure that each array element is a object that has a prroperty that is an array consisting of his children:
React.js call recursive function in render
I'm already able to generate the view, but now my problem is setting the onClick={
} property for each element.
For some reason, the elements of the first level of the tree works well with the onClick function, but starting at level two, whenever I click any element, the function that is bound to the click is called two, three, four times, dependends on the current element's tree level.
MY function with the onClick:
printTree: function(level){
var self = this;
var level_length = level.length;
if(level_length >= 1){
return(
<ul>
{
level.map(function(category){
return (
<li key={category.fields.name} onClick={self.editCategory.bind(self,category)}><a>{category.fields.name}</a>
{ self.printTree(category.sons_array)}
</li>
)
})
}
</ul>
)
}
}
The input parameter level is always an array..that consists of a level of the tree,a collection of objects that will be processed this iteration.
I think that my problem is calling the function recursively passing self. In the first time that the function is called, self points to the actual this and everything works fine, but starting ata level two in the recursion, self will be pointing to the previous function in the recursive call and not to the this, but I don't know how to fix it.

Jquery function - When called second time, not receiving fresh data, uses old?

I'm having trouble with a function that I'm calling multiple times. Every time I call it, it should receive fresh data (even if its the same as earlier) but somehow, next call to the function will result in what was expected output from the first call to the function.
The code:
$.calc=function(arrayName){
console.log(arrayName);
for(i=0;i<arrayName.length;i++){
if(i==2){
arrayName[i]="";
}
}
}
var arr=new Array();
arr[0]="saab";
arr[1]="saab";
arr[2]="saab";
arr[3]="saab";
arr[4]="volvo";
arr[5]="volvo";
//First run
$.calc(arr);
//Second run
$.calc(arr);
If you run the code (http://jsfiddle.net/76bme/) and open console logger/devtools you can see that I'm printing out the contents of the array that I passed along with the function, BEFORE doing anything with the array.
Next time I call the function, I pass the same array (arr) to the function as in the first call to the function, so I expect that console.log in the beginning to print out the same contents from the array. But now the array holds everything as earlier except at index 2 where I modified it to "" AFTER I printed it out with console.log. If it was the other way around I would get it (having console.log after the for-loop) but now I'm just confused!?
So what am I doing wrong?
That is because arrayName is a reference to your array object. So when you change something in that object, your arr is affected aswell. If you don't want this behaviour, you need to "create a copy" of your array :
$.calc=function(arrayName){
console.log(arrayName)
var myArr = Array.prototype.slice.call(arrayName); //Just here!
for(i=0;i<myArr.length;i++){
if(i==2){
myArr[i]="";
}
}
}
Fiddle : http://jsfiddle.net/76bme/5/
Change
console.log(arrayName);
to
console.log(arrayName.join(";"));
And you will see what you expect. The console [depending on state] does not show a snapshot of the object/array at the current time it was logged, sometimes it stores a reference to it so it will have the current values.

Categories

Resources