Calling concatenated variables in Javascript - 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>';
}
}

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?

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

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 = [];
}
});

Seeking assistance with building nested array in JavaScript

This is a question that has come up a few times on here in the past but I just can't get my head around it.
This is how my output is looking at the moment:
0 "affiliate_hoover_plugin_options[1][radioName]:mac"
1 "checked:true"
2 "affiliate_hoover_plugin_options[2][radioName]:pc"
3 "checked:false"
4 "affiliate_hoover_plugin...ons[3][radioName]:linux"
5 "checked:false"
And this is how I want it to look:
1: "affiliate_hoover_plugin_options[1][radioName]:mac", "checked:true"
2: "affiliate_hoover_plugin_options[2][radioName]:pc", "checked:false"
3: "affiliate_hoover_plugin...ons[3][radioName]:linux", "checked:false"
This is how my code looks:
var newForm = [];
for (var i = 1; i < oldForm.length; i += 1) {
newForm.push(oldForm[i].name + ":" + oldForm[i].value);
if (oldForm[i].type === "radio") {
newForm.push("checked" + ":" + oldForm[i].checked);
}
}
console.log(OnewForm);
Now I'm going to have put an extra for loop in there aren't are, which is where I'm confusing myself.
I think I just need a break
like this?
var newForm = [];
for (var i = 1; i < oldForm.length; i += 1) {
if (oldForm[i].type === "radio") {
newForm.push( [ oldForm[i].name + ":" + oldForm[i].value, "checked:" + oldForm[i].checked ] );
} else {
newForm.push( [ oldForm[i].name + ":" + oldForm[i].value ]);
}
}
var newForm = [];
for (var i = 0; i < oldForm.length; i++) {
var array = [];
array.push(oldForm[i].name + ":" + oldForm[i].value);
array.push("checked" + ":" + oldForm[i].checked);
newForm.push(array);
}
console.log(newForm);
might work

Iterate through a string and add tags using javascript

I'm working on a website project and I have a paragraph containing a list of items (it would work great as a ul, but needs to stay a p) that needs to have the first letter of each item bold. I've created a function to do this:
function inserter(string, splitter, skip) {
var array = string.split(splitter);
var len = array.length;
for(var i = 1; i < len; i++) {
var a = array[i];
var b = '<b>';
var c = '</b>';
if(a.substr(0, 3) != skip){
array[i] = splitter + b + a.substr(0,1) + c + a.substr(1);
} else {
array[i] = splitter + a;
}
}
var strFix = array.join("");
return strFix;
}
$(function(){
var text = $(".caps").html();
text = inserter(text, ': '); //bold the item after ': '
text = inserter(text, ', ', 'and'); // now bold after the comma ', ' and the skip variable which matches first three letters so the last and doesn't get bold
text = inserter(text, ', and '); //now for the item after the last 'and'
$(".caps").html(text);
});
But it needs to be called and the string iterated for every different splitter (which could ruin performance on pages with more than a few of these), and I'm wondering how I could just call it once so all the splitters are looked at during one iteration?
Example page:
http://heidikratzke.com/about.php
When you see the page, you will see that I will be doing this on multiple paragraphs within a jQuery slideshow.
If it doesn't seem like this will be a performance hit for slower browsers, I'll leave it as is.
Appreciate any suggestions on how to do it better.
One optimization you could make is to use the splitter you use to split the string into an array to join the array once the operation is finished:
function inserter(string, splitter, skip) {
var array = string.split(splitter);
var len = array.length;
for(var i = 1; i < len; i++) {
var a = array[i];
var b = '<b>';
var c = '</b>';
if(a.substr(0, 3) != skip){
array[i] = b + a.substr(0,1) + c + a.substr(1);
} else {
array[i] = a;
}
}
return array.join(splitter);
}
There's probably more you could do here as well, but this jumped out at me.
further optimization
The following gets variable declaration out of the loop:
function inserter(string, splitter, skip) {
var array = string.split(splitter);
var len = array.length;
var i, a, b='<b>', c='</b>';
for(i = 1; i < len; i++) {
a = array[i];
if(a.substr(0, 3) != skip){
array[i] = b + a.substr(0,1) + c + a.substr(1);
} else {
array[i] = a;
}
}
return array.join(splitter);
}

Categories

Resources