Getting all variables with a name - javascript

I'd like to display each variable created by
while (i < document.getElementById("box").value.split("").length) {
this["numb_" + i] = document.getElementById("box").value.split("")[i];
i++;
};
to display in document.getElementById("text").innerHTML to make a result that looks like this in the webpage :foo + variable1created + foo + variable2created + foo + variable3created etc...The whole goal is to take numbers from the text box, split the digits, and display each digit separately (means with other text between), all automatically. End result text is loopable.
Here is my codepen so you can take a look at it (I made the code very simple :) here http://codepen.io/ninivert/pen/bdEYqx

I guess this is what you are looking for
var i = 0;
var num = this["numb_" + i];
while (!!num) {
process(num);
num = this["numb_" + (++i)];
};

Thanks to Katerina Tort for the help !
Updated the codepen to contain answer.
http://codepen.io/ninivert/pen/bdEYqx
function myFunction() {
var i = 0;
while (i < document.getElementById("box").value.split("").length) {
this["numb_" + i] = document.getElementById("box").value.split("")[i];
i++;
};
fillText();
}
function fillText(){
var i = 0;
var num = this["numb_" + i];
var result = '';
while (!!num) {
console.log(num)
result += process(num);
num = this["numb_" + (++i)];
}
document.getElementById("text").innerHTML = result;
}
function process(num) {
return 'foo' + num;
}

Related

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

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>';
}
}

Each key value, join values inside loop

So i have a string, and I'm trying to join the content; if the val length is less than 10 chars, join it with the next value. But when i try this code, it joins with the same val instead of the next one.
//Set the regex.
myregex = /(<p>.*?<\/p>)/g;
//Variable string.
content = Example: <p>Hello</p><p>This is my test content</p><p>etc</p>
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
var n = val.concat(val);
$('#mydiv').append('<div>' + n + '</div>');
} else {
$('#mydiv').append('<div>' + val + '</div>');
}
})
This line here: val.concat(val), is indeed duplicating your content. What you need to do is grab the next value from the regex instead of the current one. Something like the following should work.
var matches = content.match(myregex),
myDiv = $('#mydiv');
for (var i = 0, len = matches.length; i < len; i++){
if (i + 1 < len && matches[i].length < 10){
myDiv.append('<div>' + matches[i].concat(matches[i+1]) + '</div>');
i += 1;
}
else myDiv.append('<div>' + matches[i] + '</div>');
}
val and val are the same thing, so of course val.concat(val) will duplicate it.
If you want to use $.each, I think it might be better to join with the previous value, because you don't know what the next one will be yet.
var previous = [];
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
previous = val;
} else {
if(previous.length) {
val = previous.concat(val);
}
$('#mydiv').append('<div>' + val + '</div>');
previous = [];
}
});

Javascript addition query

Don't feel foolishness in my question. Below is my scenario. Please advice
var num = 02;
var add = num + 1 ;
Getting result is 3, but I need it as 03. Is it possible.
You'll need to write a padding function:
function strpad(string, length, padChar)
{
var o = string.toString();
if(!padChar)
{
padChar = '0';
}
while (o.length < length)
{
o = padChar + o;
}
return o;
};
And then call it using:
var num = 3;
var add = strpad((3 + 1), 2); // will return '04' as a string.
you can do it like this
<script>
var num=2;
var add= parseInt(num + 2);
if(parseInt(add) <10)
{
add= '0'+add; // if single digit no. then concat 0 before the no.
}
</script>

javascript for loop "jump over value"

hi guys I have a small piece of code in jquery and I have a problem. It seems that for loop jumps over the second parameter ( when i = 2), can you tell me what's wrong?
here is code:
var items = $(".item").length;
var currentIndex = items;
place(currentIndex);
function place(index){
var s1 = Math.floor(items / 2);
for (i = 1; i <= items; i++){
(function(i, index){
if (i <= s1){
var id = findNext(1, i);
console.log("i = " + i + " > id = " + id);
} else if ( i > s1){
console.log("i = " + i);
}
})(i, index);
}
}
function findNext(index, times){
var result = index;
for (i = 1; i <= times; i++){
if (result == items){
result = 1;
} else {
result ++;
}
}
return result;
}
console output shows this :
i = 1 > id = 2
i = 3
i = 4
so it seems that for loop jumps over the second parameter (when i = 2) can you tell me what's wrong?
In your primary loop inside the function place, you define a global variable i. You do the same inside findNext thus overwriting the original i variable. Define i using the var keyword so it is only accessible inside the scope in which it was created.
for (var i = 0; i <= items; i++) {
var id = findNext(1, i); assignment returns 3 when i=2 because of scooping.
Please refer this link: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

Categories

Resources