For loop with two variables in an array [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I am a bit new in JavaScript, trying to do the hardcoded part above in a more scalable way with the function below. The 't' + i functions well but do the same with the .t + i
function showInfo(results) {
var data = results.data
document.getElementById('t1').innerHTML = [data[0].t1].join(', ')
document.getElementById('t2').innerHTML = [data[0].t2].join(', ')
document.getElementById('t3').innerHTML = [data[0].t3].join(', ')
document.getElementById('t4').innerHTML = [data[0].t4].join(', ')
}
function showInfo(results) {
var data = results.data
for (let i = 1; i < data.length; i++) {
document.getElementById('t' + i).innerHTML = [data[0].t + i].join(', ')
}
}

do instead:
function showInfo(results) {
var data = results.data
for (let i = 1; i < data.length; i++) {
document.getElementById('t' + i).innerHTML = [data[0]['t' + i]].join(', ')
}
}

Related

JavaScript how to creating dynamic variable

I am trying to create dynamic variable, for example rather saying
let f0, f1 = '';
and then using these variable in forEach
{Object.keys(shop).forEach((element, key) => {
if (element == dName[0]) {
f0 = Object.values(shop)[key];
}
if (element == dName[1]) {
f1 = Object.values(shop)[key];
}
})}
trying below,
let k = 'f';
let i = 0;
for(i = 1; i < 2; i++) {
eval('let ' + k + i + '= \'\' ;');
}
console.log("f1=" + f1);
but console printing
f1=undefined
what wrong I am doing, thanks in advance
i don't know if it is possible with eval but you could use an object to store your variables like this
let k = 'f'
let vars = {}
for(i = 1; i < 5; i++) {
vars[k+i] = ''
}
console.log(vars)
console.log("f1=" + vars.f1);

Print pattern lines using delay loop callback javascript [duplicate]

This question already has answers here:
async loading javascript with document.write
(5 answers)
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 3 years ago.
I have a code to print a pyramid pattern using callback in javascript.
Right now I am able to load entire code after 2 sec.
I need to print pattern rows after 2 sec interval of time instead loading it at a whole using call back and promises . How can I do it ?
var n = 5;
for (var i = 0; i < n; i++) {
getStar(i, n).then(star => console.log(star));
}
function getStar(i, n) {
return new Promise((resolve, reject) => {
var str = '';
for (var j = 1; j < n - i; j++) {
str = str + ' ';
}
for (var k = 1; k <= (2 * i + 1); k++) {
str = str + '*';
}
setTimeout(() => {
resolve(str);
}, 2000)
})
}

Divide Array and put it in object [duplicate]

This question already has answers here:
Splitting a JS array into N arrays
(23 answers)
Closed 6 years ago.
Below is the working code for dividing array into chunks. Please let me if you have any better solution for this.
var a = [];
for (var i = 0; i < 4500; i++) {
a.push(i);
}
var ttt = {};
var start = 0;
var end = 999
if (a.length > 999) {
for (var i = 0; i < 4; i++) {
ttt[i] = a.slice(start, end);
start = end + 1;
end = start + 999;
console.log(start + ":" + end);
}
}
console.log(a.length);
console.log(ttt[1].length);
You could use Array#splice() instead of Array#slice() if you do not need the array anymore.
var a = [],
ttt = {},
i;
for ( i = 0; i < 4500; i++) {
a.push(i);
}
i = 0;
while (a.length) {
ttt[i++] = a.splice(0, 1e3);
}
document.write('<pre> ' + JSON.stringify(a, 0, 4) + '</pre>');
document.write('<pre> ' + JSON.stringify(ttt, 0, 4) + '</pre>');

Uncaught TypeError: Cannot read property 'addClass' of undefined [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
What's wrong with this string: items[i].addClass('in'); ? it's killing me! I was tring different ways with .each(); for example but it's still fail...
if(layer = 'aboutAuthor') {
var items = $('.aboutAuthor .item');
var K = 100; // Коэфициент.
var t = K * (items.length + 1);
for (var i = items.length - 1; i >= 0; i--) {
console.log(items[i]);
setTimeout(function(){
items[i].addClass('in');
}, t);
t += K;
}
}
strange moment that console.log() displays each element in logs as expected, and normal. HELP!
I tried to not change the code too much, but I had assumed that you wanted to change the items in reverse.
if(layer === 'aboutAuthor') {
var items = $('.aboutAuthor .item');
var K = 100; // Коэфициент.
var t = K * (items.length + 1);
var i = items.length - 1;
$(items.get().reverse()).each(function() {
var item = $(this);
console.log(item);
setTimeout(function(){
item.addClass('in');
}, t);
t += K;
}
});
}

How can I loop through numbered variables in javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 9 years ago.
I have data that is being returned from a JQuery .ajax function as an array.
Now the fields in that array are named & numbered i.e part1, part2, part3, etc.
I have some code below that I thought may loop through it but it returns NaN.
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0].part + a) + '</div>';
}
I couldn't get any of the sugegstions to work so I did this instead.
var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;
I know it is a bit long winded but when I am dealing with multiple songs also I can loop them all with the array keys.
Try it this way:
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0]['part_' + a]) + '</div>';
}
You can iterate/loop through the items of array like this. You should use the property 'length' of array variable which tells how many items an array have...
var myStringArray = ["part1", "part2", "part3"];
for (var i = 0; i < myStringArray.length; i++) {
alert(myStringArray[i]);
//Do something
}
What about the following:
var array=["part1", "part2", "part3"];
html=array.map(function(o){ return '<div class="part">'+o+'</div>' }).join("")
console.log(html);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fmap
Make sure you array exploded has 10 elements becuase the index of an array start with Zero so for 9 elements you can write the code like this
for (var a = 0; a <= exploded.length; a++) {
newtext += '<div class="part">' + (exploded[a].part + a) + '</div>';
}
alert(newtext);
Modified Response to access the propery dynamically ---------
var newtext='';
alert('hi');
var exploded= {"title":"Cornerstone","firstline":"","keysignature":"C","copyright":"","part_1":"sandeep","part_2":"","part_3":"","part_4":"","part_5":"","part_6":"","part_7":"","part_8":"","part_9":"","ref":"2"};
var prop='';
var newhtml='';
for (var a = 1; a <= 9; a++) {
prop='part_' + a;
newhtml+='<div class="part">' + (exploded[prop]) + '</div>';
}
alert(newhtml);

Categories