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.
}
Related
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count = 0;
var array = person.split(",");
var freq = [];
var words = [];
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i = 0, j = 0;
while (array.length > 0) {
var temp = array[0];
while (j < array.length) {
if (temp == array[j]) {
count = count + 1;
array.splice(j, 1);
//console.log(array);
j = 0;
}
else {
j = j + 1;
}
}
freq[freq.length] = count;
count = 0;
words[words.length] = temp;
}
window.alert(freq + "\n" + words);
The problem is that whenever I run it an infinite loop occurs and no output is shown, I cannot find the error please help if possible. This code is for finding the frequency of the words in a input string with words separated by commas. thank u.
You just need to put var i=0,j=0; inside the while !
while(array.length>0)
{var i=0,j=0;
Working fidddle
You're resetting your loop variable j to 0 on each iteration. This condition if(temp==array[j]) never fails so j is always reset to 0, so while(j<array.length) is always true.
After coming out of the inner While loop, you need to reset j to zero. As the incremental value of j is not allowing it to go again inside the inner loop So array.length is not reducing And we are getting an infinite loop.
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count=0;
var array = person.split(",");
var freq = new Array();
var words = new Array();
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i=0,j=0;
while(array.length>0)
{
var temp=array[0];
while(j<array.length)
{
if(temp==array[j])
{
count=count+1;
array.splice(j,1);
//console.log(array);
j=0;
}
else
{
j=j+1;
}
}
freq[freq.length]=count;
count=j=0;
words[words.length]=temp;
}
window.alert(freq+"\n"+words);
It's where for is more useful for consistency. You can replace inner while loop by this for loop:
for(j=a.length-1; j>=0; j--)
if(temp==a[j]) {
count=count+1;
a.splice(j,1);
}
Nevertheless, overall complexity of your counting method can be reduced with data structure like map.
Essential part of your script can be reduced to this:
var counter = new Map();
for (i in array)
counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());
This is what I have currently but I cant get v(i) to behave the same as v1. What am I doing wrong?
I've also tried the piece below which also did not work.
var x = "v" + i;
alert(x);
My main problem is the following:
var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200
for (i = 0; i < 4; i++) {
if ( v(i) != ""){
alert(v(i));
}
}
Thanks in advance:)
What you are trying to do is not easily accomplished. You would have to assign the variable to the window object and then print it from there.
A much better solution is to use your own object or array to handle this:
var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200
var array = [v1,v2,v3];
for (i = 0; i < 4; i++) {
if ( array[i] != ""){
alert(array[i]);
}
}
All global variables are properties of window object you could use window['v'+ i] or this['v'+ i] to create them.
But this is very bad pattern consider using object instead.
What you are trying to do is get an interpolated variable name, which is not possible in javascript the way you do it.
You can do this using this['v'+i] or window['v'+i] which are both bad ideas in the global scope.
v(i) actually means: run function v(...) with parameter i
If i would write your example code in easy to understand javascript, i would come up with this:
for(var i = 1; i <= 4; i++)
{
var html = document.getElementById('thing'+i).innerHTML;
alert(html);
}
If you want your values in an array, in a way that you don't write the same code 6 times:
var ids = ['thing1','thing2','thing3','thing4'];
// es5
var values = [];
for(var i = 0; i < ids.length; i++)
{
var html = document.getElementById( ids[i] ).innerHTML;
values.push( html );
}
// values now contains all the values of the elements
// OR es 6
var values = ids.map(function(id) { return document.getElementById(id).innerHTML; });
// or
var values = ids.map(id => document.getElementById(id).innerHTML);
You could use an array without using single variables and loop it.
var array = [
'100', // document.getElementById("thing1").innerHTML,
'150', // document.getElementById("thing2").innerHTML,
'200' // document.getElementById("thing3").innerHTML
],
i;
for (i = 0; i < array.length; i++) {
if (array[i] !== "") {
console.log(array[i]);
}
}
If you need some keys, you could use an object.
var object = {
v1: '150', // document.getElementById("thing1").innerHTML,
v2: '200', // document.getElementById("thing2").innerHTML,
v3: '250', // document.getElementById("thing3").innerHTML
},
i;
for (i = 1; i <= 3; i++) {
if (object['v' + i] !== "") {
console.log(object['v' + i]);
}
}
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
<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
var points = new Array(100);
var label = points.length;
for (var i = 0; i < label; i++) {
console.log(points[i]);
}
</script>
</body>
</html>
This is my First question in Stackoverflow. As i am an beginner, Please bare me and i need alot of support from you people. I m trying to print 1 to 100 numbers using arrays in javascript only. I'm Facing some errors in the above code. Please correct my mistakes to get the output..Thankyou in advance.
This will print 1-100 without any loops
Array.from({length: 100},(_,x) => console.log(x+1))
he said he wants to print 1-100 from an ARRAY...So the array needs to be populated, first. THEN, you can loop through the array.
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1; //This populates the array. +1 is necessary because arrays are 0 index based and you want to store 1-100 in it, NOT 0-99.
}
for (var i = 0; i < points.length; i++) {
console.log(points[i]); //This prints the values that you stored in the array
}
The array values are uninitialized. I'm assuming that you want to print the values 1 to 100 using arrays where the values 1 to 100 are inside the array.
First initialize the array.
var oneToHundredArray = [];
Now populate it with values 1 to 100.
for(var value = 1; value <= 100; value++) {
oneToHundredArray.push(value);
}
Now the contains the values you want. Just loop and print over it now.
for(var index = 0; index < oneToHundredArray.length; index++) {
console.log(oneToHundredArray[index]);
}
Done :)
Array.from(Array(100), (_,i) => console.log(i+1));
The second parameter acts as mapping callback, so you also do this...
const arr = Array.from(Array(100), (_,i) => i+1);
for(num of arr) {
console.log(num);
}
Reference: Array.from
You should start off with an empty array, then run a loop for 1-101, I logged the iterator so you can see the values populate, you then need a binding agent to hold the value of the iteration, then you would need to push those values to your empty array.
var numbersArray = [];
for( var i = 1; i <101; i++){
console.log(i);
var numbers = i;
numbersArray.push(numbers);
}
After that, you then need to run a loop for the length of the numbersArray to output the individual results.
for(var m=0; m<= numbersArray.length -1; m++){
console.log(numbersArray[m]);
}
output console.log logs numbers 1-100 respectively.
var label = new Array(100);
for (var i = 0; i < 100; i++) {
label[i] = i + 1;
}
for (var i = 0; i < label.length; i++) {
console.log(label[i]);
}
It's much more easier with "while"
var i = 1;
while (i < 100) {
document.write(i + "<br/>");
i++;
}
Using a for loop:
function get_array() {
var arr = [];
for(var i=1; i<=100; i++) {
arr.push(i);
}
console.log(arr);
}
get_array()
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;
}