When iterating through array, first value is always "undefined" - javascript

I created a quiz and I'm trying to iterate through the elements in the HTML form (radio buttons), adding the value of the button to a string if it is checked. However, the first thing added to the string is always "undefined" and I can't work out why. Please note, I'm very new to Javascript.
I've tried changing the way the for loop works - using (inputs.length+1), or setting i to 1 instead of 0. This doesn't seem to be the issue however. I've also tried checking that the value isn't undefined before adding it to the string (as shown below), but it still results in the first part of the string saying "undefined".
var chosen_result; //the string to add values to
var temp;
var inputs = document.forms["townquiz"].elements;
for (i = 0; i < (inputs.length-1); i++) {
temp = inputs[i];
if((temp.checked) && !(temp.value == "undefined")){
chosen_result += temp.value;
Actual Result: undefinedABC
Expected Result: ABC
where A, B and C are values of the radio buttons in the HTML form.

In regards to strings, the += operator concatenates the current value and a new value. chosen_result is undefined because it was declared but not initialized. Simply set chosen_result to an empty string:
var chosen_result = ""; //the string to add values to
var temp;
var inputs = document.forms["townquiz"].elements;
for (i = 0; i < (inputs.length-1); i++) {
temp = inputs[i];
if((temp.checked) && !(temp.value == "undefined")){
chosen_result += temp.value;

Assign an empty string to chosen_result like chosen_result = '' to avoid the value being undefined when you append to it.

String addition in JavaScript can be somewhat strange, because it uses coercion. When you declare chosen_result, you're not setting it to anything, so its type is undefined. When you add a string to undefined, JavaScript will turn it into a string, then concatenate it. String(undefined), however, is "undefined", so, what you're really doing is
"undefined" += "ABC"
To fix this problem, initialize chosen_result as an empty string:
var chosen_result = ""
This way, it won't be coerced.

Related

Why when I print an element of an array it starts with undefined and then the numbers that I insert

Why when I print an element of an array it starts with undefined and then the numbers that I insert. I even tried to cosnole.log(search[j]) and its exactly what I want. But for some reason I think the first += that I do is undefined.
function new_vid(){
let x=1;
console.log("################################################################");
for(let i=0; i<search1.length; i++){
if(search1[i]=="s" && search1[i+1]=="n" && search1[i+2]=="i" && search1[i+3]=="p" && search1[i+4]=="p" && search1[i+5]=="e" && search1[i+6]=="t"){
for(let j=i+36; j<i+46; j++){
console.log(search1[j]);
dates[x]+=search1[j];
}
x++;
}
}
console.log(dates[0]);
console.log(dates[1]);
console.log("##################################################################");
}
the output is:
undefined2021-08-04
undefined2021-08-01
dates[x] is undefined before the first insert. And dates[x] += search1[j] in principle does the following:
dates[x] = dates[x] + search1[j]
But undefined + "foo" results in undefinedfoo in JS. Use
dates[x] = (dates[x] || "") + search1[j]
This way dates[x] || "" will return the empty string if dates[x] is undefined, and thus concatenate the empty string with search1[j]
But as you say you are coming from a c++ background, I wonder a little bit about your careless usage of indexes without any bound-checking. And your algorithm will go out of bounds, because you are iterating your index i all over the search1 array, and then access an index i+1, i+2 or even i+36.
This will not crash in JS, but be aware that search1[j] will as well return undefined if the index j is out of bounds of your array, so you may need
dates[x] = (dates[x] || "") + (search1[j] || "")
as well.
If the variable dates is array, the 1st element basically is undefined since you haven't declared before. ​
You can do the check before adding into the dates
if(dates.length == x+1)
​dates.push(search1[j]);
else
​dates[x]+=search1[j];
If you are wondering about push, it's just the same mechanism as the function push_back() in C++ Vector.
One more thing is, this line of code will make you always find the undefined when you do the console.log in the next line.
for(let j=i+36; j<i+46; j++){
When it happen? It will happen if it's any possibility for the search1 to contain the word snippet at the end of string, then the string will not have anything at the i+36 or higher indexes.

unable to get value of i in for loop

I have a simple for loop and it is matching condition according to my log files
but still the value of i is showing undefined
here is my javascript code
var indexs,i;
for(i = 0; i < data[0].length; i++){
if (new Date(data[0][i]) == new Date(inRecord.rdate))
{indexs = i;
}
Logger.log(new Date(data[0][i])+ " : " +new Date(inRecord.rdate) +": indexes:"+indexs)
}
and Image below if my log output which shows the condition should matched.
what am I doing wrong here?
new Date returns an object. And two objects can not be compared even where they contain the same data. The result will always be false.
new Date creates an object which cannot be compared. Even if two of these objects are identical, they will not produce a true comparison. To get around this, define them before the IF statement and compare the millsecond values with getTime(). This will be comparing two numbers (not objects) and work great :)
let dataDate = new Date(data[0][i])
let recordDate = new Date(inRecord.rdate)
if (getTime(dataDate) == getTime(recordDate)) {
indexs = i;
}
Happy to clarify if this doesn't work.

Referencing a number in a JavaScript multidimensional object

The code I have below uses a number as a dataset in a JavaScript object:
spacenum = spacedetails[1];
//Create object for space number
if(spacenum in spaceobj['P1'] == false){
spaceobj['P1'][spacenum] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
spaceobj['P1'][spacenum]['Vacant'] = spacedetails[2];
spaceobj['P1'][spacenum]['Name'] = spacedetails[3];
spaceobj['P1'][spacenum]['Number'] = spacedetails[4];
spaceobj['P1'][spacenum]['Apartment'] = spacedetails[5];
This code goes around in a loop so 'spacenum' starts at 1 and goes up to the late 100s.
I am trying to access the data like so:
console.log(spaceobj.P1.11.Vacant);
However, the '11' is throwing up errors. I've tried brackets and quotes without any luck.
How can I access the data I want using a number?
In javascript '11' is not a valid variable name. However, because of its dynamic nature you can use:
console.log(spaceobj.P1["11"].Vacant);
Alternatively, one can also use:
console.log(spaceobj["P1"]["11"].Vacant);
Actually your line code below is undefined
spaceobj['P1']
Be sure your spaceobj['P1'] = false; has value
spacenum = 11;
spaceobj = [];
spaceobj['P1'] = false;
spaceobj['P1'][spacenum]= 'A';
spaceobj['P1'][spacenum]= 'B';

String variable prefixed with undefined in for loop

I have a drop-down on which i use .Change() to trigger a function. Function basically get certain data using getJSON and based on those value in have to create string of array for mp3 file.
Below code is generating string but always prefix undefined to string.
In code you will notice setTimeout which is just to provide certain delay till data received. In below example i am using static value and it still prefix undefined. not sure why may be i have defined variable in wrong manner.
Complete example JSBin
$('.customSurah').change(function(){
//surahNo = $('#surah option:selected').val();
setTimeout(function(){
//countSpan = $('#surah-wrapper').children().length;
surahNo = 1;
countSpan = 7;
var i=0;
for (i = 0; i <= countSpan; i++) {
strCat += surahNo+"/"+i+".mp3,";
console.log(strCat);
}
}, 3000);
});
OUTPUT
undefined114/0.mp3,
undefined114/0.mp3,114/1.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,114/6.mp3,
You have a variable strCat that is not initialized, and then you append a value to it in this line:
strCat += surahNo+"/"+i+".mp3,";
Since strCat is not initialized in first round of loop, you get undefined prepended to your string.
To fix this, you need to initialize the variable to empty value first:
var strCat = ''; // <- initialize your variable to empty value
surahNo = 1;
countSpan = 7;
The outcome is perfectly valid as per javascript is concerned.
Why?
I guess you probably know if you declare any variable in javascript and you don't assign its default value then automatically undefined is assigned. So, that is a valid. What happens when you do that:
var somevar; // non assigned default value set to -> undefined
console.log(somevar); // logs undefined
But,
In your case you have to give it a default value like a blank string var strCat "";. So, now when you do this:
var somevar = ""; // assigned default value to set to -> ""
console.log(somevar); // logs ""
So, the solution to your issue is, you have to initialize/assign a default value to your variable. like:
var strCat = "";

Using a variable to search an array instead of a static string

Okay, so what I have is basically three dynamic drop down boxes and a 2D array. I have each box adding their values together, and then I want the sum of the values to be searched for through the array to pull out the fifth value on whatever the row the value was on.
var shape = document.getElementById("shape").value;
var dimension_one = document.getElementById("dimension_One").value;
var x = 'x';
var dimension_two = document.getElementById("dimension_Two").value;
var selected_beam = shape + dimension_one + x + dimension_two; // combine all values from text boxes
alert(selected_beam);
for (i = 0; i < array_shapes.length; i++)
{
if (array_shapes[i][2] == selected_beam) {
alert('Area=' + array_shapes[i][5]);
//Area= array_shapes[i][5]);
}
}
I know that selected _beam is giving me the value I want, and I also know that the array loop returns what I want out of the array but only if I replace
if (array_shapes[i][2] == selected_beam)
with
if (array_shapes[i][2] == "value I want to search for")
So what I really need to know is - why will it only accept it as a string and not as my selected_beam variable.
Based on your array values, it looks like you need var x to be uppercase like:
var x = 'X';
If I am reading your array correctly, it also looks like the beam size is in element 0 and 1 of the array not 1 and 2, so you may need to not look for array_shapes[i][2], but rather array_shapes[i][0] or array_shapes[i][1]
The first item in the array is at index value = 0.
You need to do some debugging.
To start off, you need to know why selected_beam !== "your value".
I suggest you use this function to compare the strings:
function compare( s1, s2 ){
alert("s1: " + s1.toString());
alert("s2: " + s2.toString());
if (s1.toString() == s2.toString())
return alert("true");
return alert("false");
}
>>> compare(selected_beam,"your value");
The problem might be as simple as having unnecessary characters in your selected_beam.
So where you have alert(selected_beam), try to compare the strings and see if it returns true or false.
You are concatenating values that you're parsing from a text box. The result will be a string
Try doing:
var selected_beam = parseInt(shape) + parseInt(dimension_one) + parseInt(x) + parseInt(dimension_two);

Categories

Resources