Saving a lot of variables from a series of classes - javascript

I want to save value in variables a more efficient way.
I tried writing a for loop:
for(i=1; i <= $('input').length; i++) {
var x+i = $('custom'+i).val());
}
what i got is: 'Uncaught SyntaxError: Unexpected token + '
this was actually expected that it wouldnt work but i have to try before asking here
the HTML
<input type="text" class="custom1">
<input type="text" class="custom2">
<input type="text" class="custom3">
till custom12..
I know i can do this:
var x1 = $('.custom1').val(),
x2 = $('.custom2').val(),
x3 = $('.custom3').val(),
till 12..
Is there a more efficient way to do it?

Use an array.
var x = [];
for(var i=1; i <= $('input').length; i++) {
x.push($('.custom'+i).val());
}

var x = [];
$('input').slice(0,11).each(function(index){
x.push($(this).val());
});
You can omit .slice(0,11) if there are actually only 12 inputs on the page.

You can try this
var arr = [];
var len = $('input').length;
for(var i=1; i <= len; i++) {
arr.push($('.custom'+i).val());
}
Most answer's above are correct, but all evaluating $('input').length every time,you can increase performance by evaluating it once and assign to a variable like len than use that len variable in loop.

Depending on what you want to do with the variables afterwards, you could also do:
var results = {};
for(i=1; i <= $('input').length; i++) {
results['x' + i] = $('.custom'+i).val());
}
This adds members to the ´results´ object so you can do:
var xOne = results.x1;
var xOneAgain = results['x1'];
var xOneLastTime = result['x' + 1];
Working Fiddle here.
Quentin's answer is probably the most natural one though.

var x = 0;
for(i=1; i <= $('input').length; i++) {
x += parseInt($('.custom'+i).val()) || 0;
}

Related

How i could get all element by class name of same class?

Im triying of get all element by class name but i cannot get
when i try to get a one lement this command works
document.getElementsByClassName('div1')[5].value
but this command not works
var i=0;
for ( i < 6; i++) {
x = document.getElementsByClassName('div1')[i].value ;
}
var elementHtml = x;
i obtain this error
SyntaxError: missing ; after for-loop condition index.html:9:16
ReferenceError: downloadDiv is not defined
i get this error also
****TypeError: document.getElementsByClassName(...)[i] is undefined[Saber más]
please somebody help me
=============================================================
i put the response thankyou for your answers
var i = 0;
var x = 0;
for(var i = 0; i < document.getElementsByClassName('div1').length; i++){
x = x + document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;
You have made a mistake in your for loop in relation to your question;
for (var i=0; i < 6; i++) {
x = document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

Why wont my loop within a loop in Javascript work?

This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.
for(i = 0; i < questions.length-1; i++){
radios = document.getElementsByName(questions[i]);
for (var t = 0; length < radios.length; t++) {
if (radios[t].checked) {
var qResults = JSON.parse(localStorage["qResults"]);
num = radios[t].value;
checked = num.toString();
var temp = (id[0] + ";" + questions[i] + ";" + checked);
alert(temp);
qResults.push(temp);
localStorage["qResults"] = JSON.stringify(qResults);
}
}
alert("question finished");
}
Your inner loop is wrong. Change this:
for (var t = 0; length < radios.length; t++) {
to:
for (var t = 0; t < radios.length; t++) {
Side note: I would suggest that you read the local storage before the loops, and write it back after the loops, instead of doing it for every question.
In addition to Guffa's fix, I think it makes more sense if you can move var qResults and localStorage["qResults"] outside of the second for loop:
var qResults = JSON.parse(localStorage["qResults"]);
for loop I {
for loopII {}
}
localStorage["qResults"] = JSON.stringify(qResults);

setting a variable to each element of an array

i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.

for loop help, unknown syntax with javascript

say I wanted to use variables like
var userpos1 : int;
var userpos2 : int;
var userpos3 : int;
//in a for loop like
var i=1;
for (i=1;i<=3;i++)
{
userposi + 1
}
how would I place the i so that the for loop goes through all of my variables properly
var userpos1var : int;
var userpos2var : int;
var userpos3var : int;
//in a for loop like
var i=1;
for (i=1;i<=3;i++)
{
userposivar + 1
}
is there something I need to do to this i to make it work properly such as a "" or a [] around it?
Create an array of those vars and go over like this
for(i = 0; i < 3; i++)
{
func(arr[i]);
}
you should use an array of variables instead, but to do what you are wanting to do, you would write:
eval("userpos" + i + "var") + 1
eval can be unsafe to use, and does not peform well.
<script type="text/javascript">
var userpos1 = 1;
var userpos2 = 2;
var userpos3 = 3;
var i = 1;
for (i=1;i<=3;i++)
{
alert (eval("userpos" + i));
}
</script>
Why don't you use an array... ?
var userpos = new Array(3);
for (var i=0; i<userpos.length; i++) {}
{
userpos[i] = i;
}
This is much easier done by storing those values in a single array and iterating over the array.
someArray = new Array(1, 2, 3);
for (key in someArray)
alert(someArray[key] );
Instead of doing it this way, use an array of user positions:
//Create an array of 3 positions,
setting all to 0
var userPos=new Array(0, 0, 0);
//loop through each position - notice
starts at 0.
for (var i = 0; i < 2; i++)
{
userPos[i] += 1;
}
Eval() would do it, but we should not encourage the use of it. Instead, construct an anonymous function.
for ( i = 1; i <= 3; i++ ) {
alert(new Function('return userpos' + i + 'var;')()); // value of userpos1var
}
Update
JSFiddle example: http://jsfiddle.net/madr/AHBrd/
What you're looking for is:
var userpos = ['a','b','c'];
for(var i=0; i < userpos.length; i++) {
userpos[i]; // doing something with it.
}

Categories