How to get rid of undefined? - javascript

When I console.log the array below, undefined is a part of each array item, I would like to know why is that and how to get rid of it?
new_colors.addEventListener("click", function() {
var rgb_guesses = new Array();
for(var i = 0; i < color_squares.length; i++) {
var rgb_value = "rgb" + "(" + random() + "," + " " + random() + "," + " " + random() + ")";
color_squares[i].style.background = rgb_value;
rgb_guesses[i] += rgb_value;
}
guess_rgb.textContent = color_squares[3].style.background;
console.log(rgb_guesses);
});

You've created an empty array
So, the statement
rgb_guesses[i] += rgb_value;
is shorthand for
rgb_guesses[i] = rgb_guesses[i] + rgb_value;
Now as the array is empty, rgb_guesses[i] will be undefined until you assign a value to it ... undefined when coerced to a string, is "undefined"
So, your code is doing the equivalent of
rgb_guesses[i] = "undefined" + rgb_value;
Since you are only ever assigning a single value to each element in the array, you can change your code to simply
rgb_guesses[i] = rgb_value;
Or
rgb_guesses.push(rgb_value);

Related

javascript split String at quotation marks // Json.parse gives undefined object

I have a string with this value:
[{"email":"SharePoint.Admin_SA.external#test.net","id":"i:0#.w|opmain\\xespsa","label":"Admin_SA, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespsa"}]
The strings all have the same format. It can also be
[{"email":"SharePoint.Admin#test.net","id":"i:0#.w|opmain\\xespec","label":"Admin, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespec"}]
But I need a "global" approach, so that it always splits it at label. For example, splitting the first one should only output Admin_SA, SharePoint.
How can one achieve this?
I tried the following, but it didn't give me the result I wanted:
var test = NWF$("#" + varRequestor).val();
var array = test.split(':');
var a = array[0];
var b = array[1];
var c = array[2];
var d = array[3];
var e = array[4];
console.log("a: " + a);
console.log("b: " + b);
console.log("c: " + c);
console.log("d: " + d);
console.log("e: " + e);
I tried using JSON.parse as well, but it didn't work:
console.log("Requestor DispName: " + NWF$("#" + varRequestor).val());
var obj = NWF$("#" + varRequestor).val();
const test = JSON.parse(obj);
console.log("obj.label:" + obj.label);
i think, you want value corresponding to label. you can try this.
let temp = [{"email":"SharePoint.Admin_SA.external#test.net","id":"i:0#.w|opmain\\xespsa","label":"Admin_SA, SharePoint","title":"SharePoint Projektteam SP","type":"User","value":"i:0#.w|opmain\\xespsa"}];
console.log(temp[0].label);

I am getting characters rather than words when I alert an array reference

On the first alert(array[0]) I get a full word. On the next alert after the loop, I get only a character with each reference. I found a similar question on here, but there wasn't an answer with it.
var listNumbers = document.getElementById("someNames").getElementsByTagName("li");
for(var i = 0; i<listNumbers.length; i++) {
z = (listNumbers[i].innerHTML);
array = z.split(" ");
alert(array[0]);
firstArray = firstArray + '"' + array[0] + '"' + ", ";
lastArray = lastArray + '"' + array[1] + '"' + ", ";
phoneArray = phoneArray + '"' + array[2] + '"' + ", ";
}
alert(firstArray[1]);
You are building your firstArray variable as a string, not an array. When you access a string with [0], you will get the character at that position in the string, not a whole word.
If you want to be able to access words, you need to declare it as an array and use .push() to add words to it.
var listNumbers = document.getElementById("someNames").getElementsByTagName("li");
var arrayOfFirstNames = [];
var arrayOfLastNames = [];
var arrayOfPhoneNumbers = [];
for(var i = 0; i<listNumbers.length; i++) {
z = (listNumbers[i].innerHTML);
array = z.split(" ");
alert(array[0]);
arrayOfFirstNames.push('"' + array[0] + '"');
arrayOfLastNames.push('"' + array[1] + '"');
arrayOfPhoneNumbers.push('"' + array[2] + '"');
}
alert(arrayOfFirstNames[0]);
I don't have your HTML so I havn't tested this code, but it should do the job if all you want is 3 arrays of first names, last names and phone numbers that you can access using square bracket notation.

why is my array.length not increasing?

Doesn't the addition of an array element by push increase the length of the array by 1 ?
var parameters = [];
if (parameters.length == 0) {
// join select menu and option then add to parameters array
var parameterSelected = nameOfSelectBox + " " + ":" + " " + $i + ",";
parameters.push(parameterSelected);
} else {
var parameterSelected = "," + " " + nameOfSelectBox + " " + ":" + " " + $i;
parameters.push(parameterSelected);
}
// check for repeats
// does a select input exist?
// add to appropriate indexes then add new or modify existing parameters
console.log(parameters.length);
});
In your current code it will never go to else because
var parameters = [];
always sets its length to 0 because you just declare parameters again. Then you add one element to the array and its length changes to 1 and that is it.
you should do something like this:
var my_array = []; // zero
my_array.push("abc"); // one
my_array.push("def"); // two

Cannot read properly "split"

I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.

Why does the array reference number switch to a STRING?

I found the problem I was having with referencing but I don't understand what's happening now. The array is being populated properly but I couldn't figure out why I couldn't pull the values. Then after some trial and error I found at the end if I closed the array reference value in quotes it would return the right value. Why is the reference being turned into a string when it's created using an integer?
function initPPArray(year) {
var beginningOfYear = new Date('January 1, 2014');
var dayOffset = (beginningOfYear.getDay() + 6) % 7;
var beginningOfPP = new Date(beginningOfYear.getFullYear(), beginningOfYear.getMonth(), beginningOfYear.getDate() - dayOffset);
var payPeriodList = [];
payPeriodList[1] = {};
payPeriodList[1].start = beginningOfPP;
payPeriodList[1].end = new Date(beginningOfPP.getFullYear(), beginningOfPP.getMonth(), beginningOfPP.getDate() + 13);
Logger.log('beginningOfPP: ' + beginningOfPP);
var txtStart = getMonthString(payPeriodList[1].start) + ", " + payPeriodList[1].start.getDate();
var txtEnd = getMonthString(payPeriodList[1].end) + ", " + payPeriodList[1].end.getDate();
Logger.log("PP 1: " + txtStart + " - " + txtEnd);
for (var i = 2; i <= 26; i++) {
payPeriodList[i] = {};
payPeriodList[i].start = new Date(payPeriodList[i-1].end.getFullYear(), payPeriodList[i-1].end.getMonth(), payPeriodList[i-1].end.getDate() + 1);
payPeriodList[i].end = new Date(payPeriodList[i].start.getFullYear(), payPeriodList[i].start.getMonth(), payPeriodList[i].start.getDate() + 13);
var txtStart = getMonthString(payPeriodList[i].start) + ", " + payPeriodList[i].start.getDate();
var txtEnd = getMonthString(payPeriodList[i].end) + ", " + payPeriodList[i].end.getDate();
Logger.log("PP: " + i + ": " + txtStart + " - " + txtEnd);
}
// This returns the proper value.. when no quotes are used it returns
// the last date of the loop "Dec 15,2014"
Logger.log("Random Value: " + payPeriodList["6"].start)
return payPeriodList;
}
Arrays in JavaScript start with index 0, not index 1. So this code:
var payPeriodList = new Array();
payPeriodList[1] = {
// ...
};
...leaves the 0th entry blank while making the array's length 2 (because standard JavaScript arrays are inherently sparse, as they aren't really arrays at all). Once you've done that, since you're using push in the subsequent code, that first entry is never filled in.
Change the 1 to a 0, or use push for the first entry (as you are with the subsequent ones).
Side note: It's almost always better to create an array with an array literal, not new Array():
var payPeriodList = [];
I think that your problem is that every item in your payPeriodList array is a reference to the same object (payPeriodItem). Each iteration through your assignment array is altering the start and end values of payPeriodItem instead of creating a new object with new start and end values. So to solve this, you would need only change the first line inside the for loop to assign a new object to payPeriodList[i].
for (var i = 2; i <= 26; i++) {
payPeriodList[i] = {};
/*...*/
}

Categories