Adding a different value of the same variable to an array - javascript

Using my micro:bit I am trying to add the value of a variable called sendText to an array without overwriting its previous stored value for that variable.
input.onGesture(Gesture.Shake, () => {
list.push(sendText)
binSend = 0
basic.showString(sendText)
})
My array is called list
let list: string[] = []
I am trying to store single characters in an array then outputting them. If there is a better alternative to using an array I would gladly accept it.

To add a value to an array you use push function, after, if you need to group the characters pushed to array for output you could to use for your specific example list.join('')

Related

How do I log the name of the variable instead of the data associated with it?

I am building a program on node.js that scans the prices of some currencies, and I am getting the prices, however I would like the program to also log the name of the currencies, not just the price. As you can see in the following code, the 'currency' variable in the console.log was my try to make the name show before logging the price.
const currencies = [euro, yen];
for (let currency of currencies) {
const pair = await fetchPairData(currency, dollar);
const route = new Route([pair], dollar);
console.log(currency + route.midPrice.toSignificant(6));
}
But it seems like the currency variable wants to return the values associated with it, not the names of the currency... How do I switch that?
Thanks for the help guys, step by step I will get good at this!
As soon as you do this:
const currencies = [euro, yen];
there is no link from currencies[0] back to euro or from currencies[1] back to yen. [euro, yen] takes the value of the euro and yen variables and puts those values in the array.
Trying for minimal changes to what you have, you could use an object rather than an array:
for (let [currencyName, currencyValue] of Object.entries({euro, yen})) {
const pair = await fetchPairData(currencyValue, dollar);
const route = new Route([pair], dollar);
console.log(currencyName, currencyValue + route.midPrice.toSignificant(6));
}
How that works:
{euro, yen} is an object literal using shorthand property notation; the longhand would be {euro: euro, yen: yen}. So you end up with an object with properties named "euro" and "yen" with the values from the euro and yen variables.
Object.entries creates an array of [name, value] pairs from an object's own enumerable properties. The array ends up being :
[ ["euro", euroValue], ["yen", yenValue] ]
(You could, of course, just do that directly rather than via Object.entries({euro, yen}).)
for-of loops through the entries in that array.
I'm using destructuring assignment in the for-of to grab the name and value into separate constants.
But, ideally you'd change your starting point so you had pairs of names (of the currency) and values (the currency value) to start with, rather than creating them based on variable names.

Passing array of strings to a function in a string literal

When I pass an array of strings and an index to an onclick event, the callback function receives the parameters from the first two values of the array as a number instead of the array and the index.
I have tried to convert it to an array using the Array.from function.
let presentantes = ["28411", "199904", "214966", "16226"];
console.log('presentantes', presentantes);
//presentantes (4) ["28411", "199904", "214966", "16226"]
let id = 1
let listNominated = `<li onClick="cargaPresentantes(${presentantes}, ${i})">`
function cargaPresentantes(presentantes, id) {
console.log('presentantes', presentantes);
console.log('id', id)
//presentantes 28411
//id 199904
}
I was expecting to get an array ["28411", "199904", "214966", "16226"] and the index 1
Actually template literals work something like this - If the variable which is passed to the placeholder is not a string(an array in this case) then it CONVERTS it to string.
So in your code the value of listNominated becomes '28411,199904,214966,16226,1' and thus it takes the first two arguements i.e. 28411 and 199904.
You cannot pass the parameters in that way... you should create a “onclick listener function” and then associate it to the “li” element.
As Andrea said I had to add an onclcik listener function. To do this, I had to append the string literal to the document first.

Passing associative array as props not working

I have a React application which handles rooms and their statistics.
Previously, I had the code set up to pass as props to the next component:
the raw statistics (not a concern for the question)
an array of all the rooms set up as follows
I figured it would be simpler for me, though, to have the list of all rooms as an associative array where the keys of each element is the same as the ID it contains. To do that, I utilized a code similar to this in a for loop:
roomsList[rooms[v].ID] = rooms[v];
So that the result would be:
[a001: {...}, a002: {...}, ...]
I then proceeded to pass this style of array, and not the standard one with a numeric index, as a prop to the next component as such:
<StatsBreakdown stats={computedStats.current} roomsList={roomsList} />
BUT
Now, the next component sees that prop as an empty array.
Even more weirdly, if I initialize that roomsList array with a random value [0] and then do the same process, I end up with:
I cannot cycle through the array with .map, and, according to JS, the length is actually 0, it's not only Google Chrome.
Is there something I'm missing about the way JSX, JS or React work?
Your original roomsList was an array of objects, whose indices were 0,1,2 etc. roomsList[rooms[v].ID] = rooms[v]; implies you are inserting elements not using a number but an alphanumeric string. Hence your resulting array is no longer an array but an object.
So we can cycle over the object using Object.keys().
const renderRoomDets = Object.keys(roomsList).map(room => {
roomOwner = roomsList[room].owner_id;
return (
<div>
<p>{`Room Owner ${roomOwner}`}</p>
</div>
);
});
But I believe your original form is ideal, because you are reaping no special benefits from this notation.
A better alternative maybe using .find() or .findIndex() if you want iterate over an array based on a specific property.
const matchedRoom = roomsList.find(room => room.ID === 'Srf4323')
Iterate the new array using its keys not indexes.
Or even better store your data in an actual object instead of an array since you're using strings for ids.
First define your object like so:
let data = {};
Then start adding records to it. I'd suggest deleting the ID attribute of the object since you're storing it in the key of your record, it's redundant, and it won't go anywhere unless u delete the entry.
data[ID] = row;
To delete the ID attribute (optional):
row.ID = null;
delete row.ID;
Then iterate through it using
for(let key in data){}

Get data from an array of dictionaries in Javascript

I'm working with a web framework and I'm using variables from Python into Javascript code.
I get next array in Python, which can contain more than one cell with dictionaries inside it:
[[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]]
I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next:
var X = JSON.parse(("{{X|decodeUnicodeObject|safe}}").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\""));
Where X is the Python variable. Unfortunately, this does not run with the array I wrote above.
How can I do that?
Thanks beforehand,
Regards.
I want to be able to access every cell array and, after that, get
every keys from the dictionary inside this cell array
If I understood correctly you want to get the keys of a nested array.
Note: your array isn't valid js.
const arrarr = [[{key1: 'val1'}, {key2: 'val2'}], [{key3: 'val3'}, {key4: 'val4'}]];
arrarr.forEach(arr => {
arr.forEach(e => {
Object.keys(e).forEach(k => console.log(k))
})
})
If the depth of nests is of arbitrary depth you can use recursion and check if the child is an array, if it is keep going, else get the keys.

Javascript object properties with same values experience the same changes when they shouldn't (splice)

I'm not sure if this is a bug or if I have a complete misunderstanding of Javascript, but this is what happens:
I take an object with two arrays inside it, one representing the current queue of IDs and another representing the total queue of IDs (hypothetical situation)
var mainObject = {
object1:[],
object2:[]
};
In a function, we set the two property arrays to the same variable which holds the array needed before we can start processing the queue.
var randomVar = [1,2,3,4];
mainObject.object1 = randomVar;
mainObject.object2 = randomVar;
Now we want to make use of the splice method to remove the first index from object1 while keeping it on object two.
mainObject.object1.splice(0,1);
The result of the object is now as follows:
mainObject = {
object1:[2,3,4],
object2:[2,3,4]
};
meaning that both of the properties were spliced when we only asked Javascript to run it once.
See JS Fiddle for live example:
https://jsfiddle.net/ypow6y8g/
Is there something I'm missing or is this just another night spent with loose JS?
You have one array, and two variables whose value is a reference to that array. When you modify the value of one of those variables, you modify the other one as it's the same.
If you want your arrays to be independent, clone one:
var randomVar = [1,2,3,4];
mainObject.object1 = randomVar;
mainObject.object2 = randomVar.slice(); // slice returns a new array

Categories

Resources