How to use join (in built method) in javascript? - 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).

Related

Javascript How to add array with another array into a new array?

So my challenge right now is unable to add array with another array into another new array.
my code:
var disabletimerange = { basedonservicetype: "", basedonservicer: "" }
var arr = [{"StartTime":"09:00:00","EndTime":"09:10:00"},{"StartTime":"10:00:00","EndTime":"15:00:00"}]
for (var xx = 0; xx < arr.length; xx++) {
var bookedStartTime, bookedEndTime
bookedStartTime = arr[xx].StartTime.slice(0, -3)
bookedEndTime = arr[xx].EndTime.slice(0, -3)
if (disabletimerange.basedonservicer === "") {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimealreadybookedtiming)
} else {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = "[" + "[" + disabletimerange.basedonservicer + "]" + "," + disabletimealreadybookedtiming + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimerange.basedonservicer)
}
Uncaught SyntaxError: Unexpected number in JSON at position 3 --> at the last line it cannot parse.
In short, what i want is basically 2 array stick tgt instead of adding into it
var y = ["hi", "123"]
var x = ["yo", "312"]
this
[["hi", "123"], ["yo", "312"]] instead of ["hi", "123", "yo", "312"]
and it must be array. not text form
You can do:
var y = ["hi", "123"]
var x = ["yo", "312"]
var result = [x, y]
console.log(result)
As you described
How to add array with another array into a new array?
create a new array
push your arrays into this new array one by one
let x = [1,2];
let y = [3.4];
let z = [];
z.push(x)
z.push(y);
console.log(z);

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

Returning a String instead of looping print statement

I'm new to Javascript and I'm curious as to how to store values in a string and then return it. In the example below 2 numbers are picked, for example 2 and 8, and the program should return 2x1 =2, 2x2=4,..... all the way up to 2x8 =16. This can obviously be done by constantly looping a print statement as I have done, but how would I be able to store all the values in a String and then return the string.
function showMultiples (num, numMultiples)
{
for (i = 1; i < numMultiples; i++)
{
var result = num*i;
console.log(num + " x " + i + " = " + result+ "\n");
}
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3,2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5,4));
function showMultiples(num, numMultiples) {
// the accumulator (should be initialized to empty string)
var str = "";
for (i = 1; i < numMultiples; i++) {
var result = num * i;
// use += to append to str instead of overriding it
str += num + " x " + i + " = " + result + "\n";
}
// return the result str
return str;
}
var mulOf5 = showMultiples(5, 10);
console.log("multiples of 5 are:\n" + mulOf5);
The operator += add the a value (right operand) to the previous value of the left operand and stores the result in the later. So these two lines are the same:
str = str + someValue;
str += someValue;
You could just use string concatenation:
var finalResult = ""
...in your loop...
finalResult += num + " x " + i + " = " + result+ "\n"
Often you can also just collect the results in an array and use join to append them.
var lines = [];
... in your loop:
lines.push(num + " x " + i + " = " + result);
... afterwards
console.log(lines.join("\n"));
In case you wanted to use ES6 syntax using backticks for a template string, you can use the below. This is a little more readable and is exactly where it is useful (so long as you can use ES6 wherever you're using JavaScript).
function showMultiples(num, numMultiples){
let result = '';
for(let i = 1; i < numMultiples; i++){
result += `${num} x ${i} = ${i * num}\n`;
};
return result;
}
console.log(showMultiples(2,8));

Constructing a URL from an array

I have an Array:
var arr[];
I have inserted many coordinates to this (x and y values)
arr[0]=12+'#'+32;
arr[1]=34+'#'+87;
arr[2]=90+'#'+89;
So when i print this array i get a string like ,12#32,34#87,90#89. These are coordinates. How do i break these and append this to a string which will be in the format.
http://host/app?x1=12&y1=32&x2=32&y2=87&x3=90&y3=89
This above URL can have many parameters. How can i construct the above URL from my array.
You can build your querystring looping through the array (here I used .each()) and using the .split() function to separate your coordinates.
var qs;
$.each(arr,function(i,v){
qs += "x" + i + "=" + v.split("#")[0] + "&y" + i + "=" + v.split("#")[1] + ((i+1)!=arr.length) ? "&" : "";
});
var url = "http://host/app?" + qs;
Similar to the above answers, loop through, split on the hash, add the pieces to the query string, and append the ampersand if you're not at the end.
for(var c = 0, query = "http://host/app?", coordinate; c < arr.length; c++) {
coordinate = arr[c].split("#");
query += "x" + (c + 1) + "=" + coordinate[0] + "&";
query += "y" + (c + 1) + "=" + coordinate[1];
if(c < arr.length - 1) query += "&";
}
The simplest approach I can think of is:
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
References:
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.push().
String.prototype.split().

Javascript Array is Breaking my Loop

So I'm having some difficulty with this two dimensional array that I've created.
I've declared it like so:
var objects = new Array();
And then I run two loops, one inside the other, and in doing so, call values to the array, but it seems to break my entire loop (and thus the script) when it does run.
for(var i = 0; i <= 32; i++) {
dirtRows++;
document.getElementById("dirtTable").innerHTML+='<div class="dr" id="dirtRow-' + i + '"></div>';
alert(i);
for(var ii = 0; ii < 32; ii++) {
dirtBlocks++;
document.getElementById("dirtRow-" + i).innerHTML+='<div class="dirt" onclick="destroyIt(' + i + ',' + ii + ')" id="dirt-' + ii + '">' + ii + '</div>';
objects[i][ii] = 1;
}
}
What might I be doing wrong? It's definitely the Array that's breaking it.
You haven't created the inner arrays.
var objects = []; // Use an array literal, not new Array()
for (var i = 0; i <= 32; i++) {
objects[i] = []; // Create sub-array
dirtRows++;
document.getElementById("dirtTable").innerHTML+='<div class="dr" id="dirtRow-' + i + '"></div>';
alert(i);
for(var ii = 0; ii < 32; ii++) {
dirtBlocks++;
document.getElementById("dirtRow-" + i).innerHTML+='<div class="dirt" onclick="destroyIt(' + i + ',' + ii + ')" id="dirt-' + ii + '">' + ii + '</div>';
objects[i][ii] = 1;
}
}
You have to declare objects[i] to be an array:
objects[i] = new Array();
objects[i][ii] = 1;

Categories

Resources