How can I loop through numbered variables in javascript [duplicate] - javascript

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 9 years ago.
I have data that is being returned from a JQuery .ajax function as an array.
Now the fields in that array are named & numbered i.e part1, part2, part3, etc.
I have some code below that I thought may loop through it but it returns NaN.
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0].part + a) + '</div>';
}
I couldn't get any of the sugegstions to work so I did this instead.
var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;
I know it is a bit long winded but when I am dealing with multiple songs also I can loop them all with the array keys.

Try it this way:
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0]['part_' + a]) + '</div>';
}

You can iterate/loop through the items of array like this. You should use the property 'length' of array variable which tells how many items an array have...
var myStringArray = ["part1", "part2", "part3"];
for (var i = 0; i < myStringArray.length; i++) {
alert(myStringArray[i]);
//Do something
}

What about the following:
var array=["part1", "part2", "part3"];
html=array.map(function(o){ return '<div class="part">'+o+'</div>' }).join("")
console.log(html);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fmap

Make sure you array exploded has 10 elements becuase the index of an array start with Zero so for 9 elements you can write the code like this
for (var a = 0; a <= exploded.length; a++) {
newtext += '<div class="part">' + (exploded[a].part + a) + '</div>';
}
alert(newtext);
Modified Response to access the propery dynamically ---------
var newtext='';
alert('hi');
var exploded= {"title":"Cornerstone","firstline":"","keysignature":"C","copyright":"","part_1":"sandeep","part_2":"","part_3":"","part_4":"","part_5":"","part_6":"","part_7":"","part_8":"","part_9":"","ref":"2"};
var prop='';
var newhtml='';
for (var a = 1; a <= 9; a++) {
prop='part_' + a;
newhtml+='<div class="part">' + (exploded[prop]) + '</div>';
}
alert(newhtml);

Related

How to change multiple values in the array JavaScript

I have an array created with a for loop that has 50 values.
var array = [];
array [0] = {
selection : 0
}
var number = 1;
for (i = 0; i < 50; i++){
array[i].selection = number;
number ++;}
How to change the value for the array[i-20].selection? I don't want to use array[30].selection
It usually works if use array[i-1].selection or array[i+1].selection but doesn't work if use anything greater than one.
Thanks
You wanted Array of Objects and not Array with single Object, right ?
var array = [];
var number = 1;
fillFrom(3, 1); // should push instead of setting and start from zero but ;-)
var res = '<table width=1><tr><td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td>';
fillFrom(0, -49);
res += '<td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td></tr></table>';
document.body.innerHTML = res;
function fillFrom(start, number) {
for (i = start; i < 50; i++) {
if (array[i] === undefined) array[i] = {
selection: number
};
else array[i].selection = number;
number++;
}
}

array displays the wrong thing

I want this code to display information from a text input from a form on an HTML page, using the array, it would take the information into an array, then display it back on a textarea, though each time it overrides the first line, not displaying right
var count = 0;
var input = document.forms["ShoppingForm"]["choiceTxt"].value;
function listChoice(){
count++;
var arr = new Array();
arr[count] = document.forms["ShoppingForm"]["choiceTxt"].value + "\n";
for(var i = 0; i <= arr.length; i++){
document.forms["ShoppingForm"]["listDisplay"].value = count + ". " +
arr[i] + "\n";
}
}
The issue seems to be with this line var arr = new Array();. Everytime it will create a new array.
Try my declaring the array outside the function.Also the seems to be no need of the count. The value can be simply pushed in the array
var count = 0;
var arr = [];
var input = document.forms["ShoppingForm"]["choiceTxt"].value;
function listChoice(){
arr.push(document.forms["ShoppingForm"]["choiceTxt"].value + "\n");
for(var i = 0; i <= arr.length; i++){
document.forms["ShoppingForm"]["listDisplay"].value = count + ". " +
arr[i] + "\n";
}
}

Why is my javascript code returning TypeError undefined? [duplicate]

This question already has answers here:
'Length' Property Undefined while iterating Array
(3 answers)
Closed 6 years ago.
class CustomTable
{
constructor(div_id, headings) {
this.div = div_id;
this.header_titles = headings;
this.item_list = new Array();
var _this = this;
this.add_item = function(items)
{
_this.item_list.push(items);
console.log(_this.item_list);
}
this.remove_item = function(item_index)
{
_this.item_list.splice(item_index, 1);
console.log(_this.item_list);
}
this.drawTable = function()
{
var t = "<table class='table' style='width:100%'>";
t += "<thead>";
t += " <tr>";
t += " <th>#</th>";
for (var i = 0; i < _this.header_titles.length; i++)
{ t += "<th>" + _this.header_titles[i] + "</th>"; }
t += " <th>Add</th>";
t += " </tr>";
t += "</thead>";
t += "<tbody>";
for (var i = 0; i < _this.item_list.length; i++)
{
t += "<tr>";
t += "<td>" + i + "</td>";
console.log(i);
var subitem_count = _this.item_list[i].length;
// ^^^^^^^^^^^^^^^^^^
// This errors out: TypeError undefined
for (var j = 0; j < subitem_count; i++)
{
t += "<td>" + _this.item_list[i][j] + "</td>"
}
t += "</tr>"
}
t += "</tbody>";
t += "</table>";
document.getElementById(_this.div).innerHTML = t;
}
}
}
var ct = new CustomTable("server_list",["Server Name","IP Address", "RAM in GB"]);
ct.add_item(["QMM-TRGEXCH01","192.168.0.225","2GB"]);
ct.add_item(["QMM-SRCEXCH01","192.168.0.226","2GB"]);
ct.add_item(["QMM-TRGAGENT01","192.168.0.227","2GB"]);
ct.add_item(["QMM-SRCAGENT01","192.168.0.228","2GB"]);
ct.add_item(["QMM-MIGCONSOLE","192.168.0.229","2GB"]);
ct.drawTable();
Please view this JSFiddle
I have searched everywhere and can't figure out why Javascript keeps erroring out. The variable is in scope and I have checked it using
_this.item_list[i].constructor === Array
and it is an Array.
I get this error at first iteration.
console.log(i); // i = 0 at error
So its not that the code is iterating out of bounds. That might be an issue with the code as well but there is something else wrong. Please look at the fiddle, I have updated it and remove the = from all for loops but I still get the same error.
It is because you are trying to invoke a method on element at unavailable index.
for (var i = 0; i <= _this.item_list.length
is supposed to be
for (var i = 0; i < _this.item_list.length
Array out of bounds issue - You are trying to access the element at index 6 which is undefined
As per your logic, if they are 5 elements in _this.item_list you are iterating elements at index 0, 1, 2, 3, 4, 5 but you should only be iterating upto 4 as the index starts at 0 and not 1
You will have to replace all instances of <= in your for-loop to <
Also your inner loop has a bug.
for (var j = 0; j < subitem_count; i++)
supposed to be
for (var j = 0; j < subitem_count; j++)
You should be incrementing j and not i in the inner loop.
Check Fiddle

Nested Loop to add numbers

I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.

Append to each element in an array in Javascript

With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.
var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];
For example: 54375:54376:54377
a = a.map(function(el) { return el + ':'; });
Or if you want to join them into a string:
var joined = a.join(':');
If you are looking for a way to concatenate all the elements with :, you can use this
var result = "";
for (var i = 0; i < a.length; i += 1) {
result += a[i] + ":";
}
result = result.substr(0, result.length-1);
Or even simpler, you can do
a = a.join(":");
If you are looking for a way to append : to every element, you can use Array.prototype.map, like this
a = a.map(function (currentItem) {
return currentItem + ":";
});
console.log(a);
If your environment doesn't support map yet, then you can do this
for (var i = 0; i < a.length; i += 1) {
a[i] = a[i] + ":";
}

Categories