iterate, split, jump between numbers jquery [duplicate] - javascript

This question already has answers here:
Access every other item in an array - JavaScript
(4 answers)
Closed 5 years ago.
Im not sure how to ask this question, thats why I didnt found the answer yet... Im trying to iterate a chain number. I mean I created a for loop and instead for showing "30, 60, 90, 120..." I want to jump from 30 to 90 and from 90 to 180. I tried to split the chain but im not doing it right. This is my code:
writeIRFField: function (name, targetElement) {
var $target = $(targetElement).split('1'),
value, values = this.get(name) || [];
$target.html('');
for(var i = 0; i < 4; i++) {
value = values[i] || 0;
$target.append('<label>' + ((i + 1) * 30) + ' ' + translator.getTranslation('days') + ' <input type="number" name="'+ name + '" value="' + value + '" min="0" step="0.01"></label>');
}
},
Where should I split or make the "JUMP" between first value in the array and the third and so on...? (More easy to understand I guess would be like "I have this chain numer: 1, 2, 3, 4, 5..." but I want to output: 1, 3, 5, 7..."

If you want jump on only odd elements (indexes) like 1,3,5,...
You can do it in iteration:
instead of "for(var i = 0; i < 4; i++) {..." ,where i = 0,1,2,3
you can do like "for(var i = 0; i < 4; i+=2) {...", so i=0,2
Another possibility is to iterate over whole list, bit skip even numbers, numbers that divides by 2, like
for(var i = 0; i < 4; i++) {
if(i % 2 == 0)
{
continue;//skip even undexes
}
value = values[i] || 0;
$target.append('<label>' + ((i + 1) * 30) + ' ' + translator.getTranslation('days') + ' <input type="number" name="'+ name + '" value="' + value + '" min="0" step="0.01"></label>');
}

Related

Calling concatenated variables in Javascript

Is there a way to include variables in each iteration of a javascript loop? For example if I put this code into a loop
if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'}
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc
and do something like
for (n = 0; n < id.length; n++) {
if (e/*concat var e w/var n?*/) {
item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
}
}
Is there a way to change the number in the var names (e1 -> e2 etc) each iteration or do i just have to keep it the long way and write everything out on its own line?
It would be possible, though highly not recommended, to use eval to come up with the variable name:
const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
console.log(eval('e' + i + 'lvl1'));
}
But it would be better to fix your script's architecture so that this isn't necessary: put each e#lvl into an array, and then access the appropriate index of the array on each iteration:
const elvl = [
'foo',
'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);
Arrays/Objects exist in javascript for a reason! Simplify your code. There is no reason to have e1, e1l, e2... as variables. Add them to an object and access them by key, or add them to an array, and loop through them. There are many javascript functions as well that will allow you to ensure all elements match a certain condition.
function submit() {
var e = {};
var idx = 28;
for (var i = 0; i <= 24; i++) {
e[i] = {};
e[i].key = document.getElementById(`ench${i}`).checked
e[i].value = $.trim(form.elements[idx].value)
idx += 2;
}
// Check condition
if (Object.values(e).some(e => e.key)) {
//One of the checked items was true
}
}
I would agree that you should change your code to use arrays.
To answer your question though, since your e1 and e1lvl variables look to be global scope, you can access them like this
window["e1"]
window["e1lvl"]
Give this a try
for (n = 0; n < id.length; n++) {
if (window["e" + n]) {
item_text += '{id:"' + id[n] + '",lvl:' + window["e" + n + "lvl"] + '},<wbr>';
}
}

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

Fastest bulk insert into javascript arrays

I wanted to check to see which was faster in adding elements to an array in javascript:
Adding a list of 5 per iteration
Adding 5 single items with adding position to the subscript
Adding one single item pr iteration
I ran it on my Linux Mint 16, Firefox 37.0.2
1 and 2 turned out much better than 3.
When I ran it 1,000,000 times 1 was noticably better than 2.
However when I ran it 10,000,000 the results were reversed. What would be the explanation for that?
var amount = 1000000;
var iter = 11;
var a = new Array(amount);
var b = new Array(amount);
var results = [];
for (j=1; j<iter; j++) {
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = [2,2,2,2,2];
}
results.push("quintuple primitive insert attempt " + j + " took " +
eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = 2;
a[i+1] = 2;
a[i+2] = 2;
a[i+3] = 2;
a[i+4] = 2;
}
results.push("single primitive insert with inline inc attempt " + j +
" took " + eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i++) {
a[i] = 2;
}
results.push("single primitive insert with single iterator attempt " +
j + " took " + eval(new Date().getTime() - clock) + "ms");
}
The code is demonstrated here:
http://jsfiddle.net/lash/cL3wewj4/
(I also tried using homogenous and heterogenous arrays to insert content, in which 2 always was the best. The attempt is in the same jsfiddle source, commented out)
You're taking times of things that are not the same:
First off, you're taking times of creating a matrix whose elements at position i%5 = 0 contain an array of five elements. The rest of the elements (i%5 != 0) are undefined. This array has a length that depends on amount due to the fact that you're adding to the variable i five in each iteration and some elements at the end of the array might not be initialized (directly or indirectly).
for (i = 0; i < amount; i += 5) {
a[i] = [2, 2, 2, 2, 2];
}
Secondly, you're creating an array whose elements are all equal to 2.
for (i = 0; i < amount; i += 5) {
a[i] = 2;
a[i + 1] = 2;
a[i + 2] = 2;
a[i + 3] = 2;
a[i + 4] = 2;
}
Thirdly, you're doing the same as two.
for (i=0; i< amount; i++) {
a[i] = 2;
}
Since one is different than 2 and 3 the results don't make sense.

loop created element's value always 5

Can someone please tell me why when I click on the [s] href created next to the list of names (myhand) generated it always says selection and i are 5?
var printDD = function(myhand, mydiv){
var dtext = "";
for(var i = 0; i < myhand.length; i++){
dtext += '[s]' + myhand[i] + ', ';
}
mydiv.html(dtext);
for(var i = 0; i < myhand.length; i++){
$('#dd'+i).click(function(){
selection = i;
console.log("sel: " + selection + " i: " + i);
});
}
}
You want to take a look at JavaScript closure inside loops – simple practical example. As the answer to that question says, you can create a function to return one, or you can use inline function invocation in the for loop like so:
for(var i = 0; i < myhand.length; i++) {
$('#dd'+i).click((function(x) {
return function () {
selection = x;
console.log("sel: " + selection + " x: " + x);
}
}(i)));
}
Because the value of i is determined at the time the click handler is run. So it will always have the value of myhand.length - 1, which is the state you left i in after the for-loop.

How to use join (in built method) in javascript?

In javascript loop i am generating a xml like this:
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
//s = s.join(' ');
}
Forgot about the t variable and all. by run this code i am getting the s value in the following format:
<row dc = "abc" al="56" msg="dkaj" />
In the second iteration it shows like this:
<row dc = "abwwc" al="56w" msg="dkajad" />
and so on till the m<t.length satisfy. What i want to join the list in each iteration. After joining all of them i should get in this way:
<row dc = "abc" al="56" msg="dkaj" /><row dc = "abwwc" al="56w" msg="dkajad" /> and so on..
I tried to do it with join written in comment section, but didn't work for me. What i am doing wrong?
The best way would be to define a string outside the loop an append to it;
var v = '';
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
v += s;
}
alert(v);
If you still want to use join(), make v an array and push() elements on to it (note that join() is an array method, not for string's)
var y = [];
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
y.push(s);
}
alert(y.join(''));
You'll be pleased to see I've tried to adhere to your variable naming conventions in my examples (i.e. meaningless characters).

Categories

Resources