I have an array in my localStorage which contains ["January","Febuary"]
I want it to be displayed in HTML preferably like this:
Month
January
Febuary
So I've tried this code:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
}
for(var b = 0; b < nameLength; b++){
document.getElementById('storageOut').innerHTML = date[b];
console.log(date[b]);
}
}
My code above does work however, the line "document.getElementById('storageOut').innerHTML = date[b];"only prints out the last data in the array, but when i check the console it prints out both.
You create the variable date in the first for-loop and assign it to one value each iteration. Easiest way would probably be to do it in a single for-loop instead:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
document.getElementById('storageOut').innerHTML = date;
}
}
Although, if you want all the dates, you should probably append it to the innerHtml:
...innerHTML += date;
Or rather:
...innerText += date;
Assuming your contents are stored in local storage key named data. Try the following.
const data = JSON.parse(localStorage.getItem('data'))
data.forEach(item => {
document.getElementById('storageOut').innerHTML += item
})
Related
I have this function
function sumFood (tot,tab_cout){
var tot = 0;
for (var i=0; i<tab_cout.length;i++) {
tot += Number(tab_cout[i]);
}
localStorage.setItem('tot',tot);
}
sumFood (GLC,GLCT);
sumFood (LIP,LIPT);
I would like that GLC, LIP go into localStorage (in place of tot) but for some reasons the result I get is undefined... what to do? (console.log gives me good result of tot)
The reason you got undefined is you have hardcoded the key this line:
localStorage.setItem('tot',tot);
where it should be dynamically changed upon the parameters. Another thing you should be aware of is, it's not a good practice to name a variable inside a function the same as its parameter which is confusing. Try this:
function sumFood (tot,tab_cout){
var total = 0;
for (var i=0; i<tab_cout.length;i++) {total += Number(tab_cout[i]);}
localStorage.setItem(`${tot}`,total);
}
sumFood(GLC,GLCT);
sumFood(LIP,LIPT);
This will save the sum in seperate keys in localStorage. In your case, I'm assuming that you want to store all the key and value pairs in only one key, which is tot in the localStorage, then the tot has to be an array of objects. Try this below:
function sumFood (tot,tab_cout){
let total = 0;
for (let i=0; i<tab_cout.length;i++) {
total += Number(tab_cout[i])
}
const savedTot = JSON.parse(localStorage.getItem('tot')) || []
const addedTot = savedTot.push({ [`${tot}`]: total })
localStorage.setItem('tot', JSON.stringify(addedTot))
}
sumFood(GLC,GLCT)
sumFood(LIP,LIPT)
// if GLC and LIP are variables, otherwise you should put them in string. Like this:
sumFood('GLC',GLCT)
sumFood('LIP',LIPT)
Then retrieve it later:
const getTot = JSON.parse(localStorage.getItem('tot')) || []
console.log(getTot) // you will see your expected output
I had to put return total to get what I needed, and I don't need to store. So I guess your solution is correct for the entitled
function sumFood (tot,tab_cout){
var total = 0;
for (var i=0; i<tab_cout.length;i++) {
total += Number(tab_cout[i]);
}
return total;
}
sumFood (GLC,GLCT);
sumFood (LIP,LIPT);
I have an array that the values range from A to Z, which I want to convert to variables that depend on the input data, for example:
enter the data
362,232,113 and this becomes an array of a length of 3 unit.
so I want to assign the name of a variable depending on the length of the input array but when executing the code, it assigns the array index well, but that same index executes the length of the input array and does not assign the variables as I would like it to.
in fact when executing this happens:
(3) 326
showing that the matrix was correctly divided but the same index was executed 3 times, in summary what I want is to be executed as follows:
"A = 326" "B = 232" "C = 113"
In advance I thank you for your help
var asignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
matrix =[326,232,113];
function divide(){
xyz = matrix.split(",");
console.log(matrix);
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
console.log(A); //(2) 326
}
}
You have a typo assignLetter instead of asignLetter ( two s ) and you need to pass a string to your function for it to work :
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
}
}
console.log({A,B,C});
You should avoid creating global variabels like that, have them in an object instead
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
var myVars = {};
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
myVars[assignLetter[i]] = xyz[i];
}
}
console.log(myVars);
I think you want to pass the parameters 326,232,113 as a whole string. You're passing them as parameters wrong.
So just do the same thing you're doing but like this: divide("326,232,113")
My array:
[
{
"date":"2018-04-01",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-02",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-03",
"time":[{"10:00":"12"},{"12:00":"25"}]
}
]
I need to get every date and time. To get this I am using a for loop. But not able to get date and time.
My script:
var slots = req.body.availableSlots;
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i]);
console.log(slots[i].date);
}
When getting date always says undefined.
It seems like req.body.availableSlots is coming as a multidimensional object array.
So full code need to be:-
var slots = req.body.availableSlots;
for(var i=0;i<count;i++){
var sub_array = slots[i];
for(j = 0; j<sub_array.length;j++){
console.log(sub_array[j].date);
}
}
Instead of using jquery library (jQuery.parseJSON()) use javascript inbuilt JSON.parse
var slots = '[{"date":"2018-04-01","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-02","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-03","time":[{"10:00":"12"},{"12:00":"25"}]}]';
slots = JSON.parse(slots);
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i].date);
Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.
I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.
I was going to try element["string1"].counter = 1; but it didn't work.
What's a good way to implement this?
If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.
Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.
You could quickly knock the array in to a set of objects with separate text and counter components.
var elements = ["string1", "string2"];
var elementsWithCounter = [];
for(var index = 0; index < elements.length; index++) {
elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
You could also create a "hash table" using a plain object such as:
var counter = {};
for(var i = elements.length; i--; ) {
counter[elements[i]] = 1;
}
Then you could increment the counter with:
counter['string1'] += 1;
or
counter[elements[0]] += 1;
This might help you.
elementArray = ["string1", "string2"]
function setCounter(str, val) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) elementArray[i].counter = val;
}
}
function getCounter(str) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) return elementArray[i].counter;
}
}
setCounter("string1", 5);
getCounter("string1");
Alternatively just access elementArray[index].counter
Javascript primitives/built in objects can't have properties/attributes added to their prototype (i.e. String.prototype.counter = -1 doesn't work correctly). Image, String, Date, Array all can't have properties added.
Maybe instead of a string you should make it an object, similar to what Orbling has posted.