join() function doesnt work in javascript - javascript

I tried using the join() function in my array and tried to document.write it but
the console says"birth.join() is not a function "
birthyear=[];
for(i=1800;i<2018;i++){
birthyear+=i
}
birth=birthyear.join();
document.write(birth);

Array.prototype.join() works on array and to insert an element to array you should call .push() instead of +=, read more about += here.
Always use var before declaring variables, or you end up declaring global variables.
var birthyear = [];
for (i = 1800; i < 2018; i++) {
birthyear.push(i);
}
var birth = birthyear.join(", ");
document.write(birth);

I your code your not appending data to array you are adding data to array variable which is wrong
1st Way
birthyear=[];
for(i=1800;i<2018;i++)
{
birthyear.push(i);
}
birth=birthyear.join();
document.write(birth);
2nd Way
birthyear=[];
k=0;
for(i=1800;i<2018;i++){
birthyear[k++]=i;
}
birth=birthyear.join();
document.write(birth);

You can't apply .push() to a primitive type but to an array type (Object type).
You declared var birthyear = []; as an array but in the body of your loop you used it as a primitive: birthyear+=i;.
Here's a revision:
var birthyear=[];
for(let i=1800;i<2018;i++){
birthyear[i]=i;
// careful here: birthyear[i] += i; won't work
// since birthyear[i] is NaN
}
var birth = birthyear.join("\n");
document.write(birth);
Happy coding! ^_^

Related

Appending an array with multiple arrays in google script

I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}

Google scripts. TypeError: Cannot call method "replace" of undefined

First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];

Appending text through loop iteration

Not sure why I'm having a hard time with this. I think it's getting late in the day probably but --
I'm pulling database values into an array. The current array is: [1,3]. I'm then stepping through the array and appending a prefix to the values (in this case: "&Plantkey=") in order for the final string to have the format of:
&Plantkey=1&Plantkey=3
Here's my code so far:
if (array[a].ParameterName == "Plantkey") {
var plantKey = array[a].ParameterValue;
var plantTemp = [];
plantTemp = plantKey.split(",");
for (var p = 0; p < plantTemp.length; p++) {
var plantKeyString = ("&Plantkey=" + plantTemp[p]);
}
}
I'm only getting the last array value (&Plantkey=3). With javascript, it doesn't like me instantiating the "var plantKeyString" and adding the "+=" operator. If I instantiate the array above the for loop, like so:
var plantKeyString;
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
Then I end up with a longer string, including the array values I want but it also pulls in the "undefined" value that it finds at the beginning so it looks like this:
undefined&Plantkey=1&Plantkey=3
I could easily look for the "undefined" and remove it but I'm sure the problem is with the loop iteration, not the data, obviously.
Any help would be greatly appreciated! Thanks!
The reason you are getting only the last value in the first case is because you are redeclaring a new plantKeyString for each loop hence only the last declaration stays.
with the second solution just do the following and it should work:
var plantKeyString="";
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
The reason you were getting the undefined at the beginning of your final result was because 'plantKeyString' is 'undefined' as you have not given it a value. In javascript all variables are undefined till you give them a value. So in the solution that I have provided you are just instantiating it with an empty string.
You can do it in a succinctly way simply using array join() method and add &Plantkey= at first as follows:
var plantKeyString = '&Plantkey=' + array.join('&Plantkey=');
For an [1,3] array this code produces what you expect: &Plantkey=1&Plantkey=3, try with this code sample:
var array = [1,3];
var plantKeyString = '&PlantKey=' + array.join('&PlantKey=');
alert(plantKeyString);
See join() description here

Need to concatenate strings from two arrays [duplicate]

This question already has answers here:
is the + operator less performant than StringBuffer.append()
(13 answers)
Closed 9 years ago.
I have two jQuery variables. Each variable is a text string containing words separated by a comma.
var myFirstVariable = green,blue
var mySecondVariable = circle,triangle
I would like to have a third variable retured like this:
var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle
The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if
var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square
Then I need my third variable to returned like this:
var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare
I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.
I'm struggling with this area of jQuery
That's simply because the jQuery library has no tools for this kind of work.
Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:
var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";
var firstArr = myFirstVariable.split(","),
secondArr = mySecondVariable.split(","),
thirdArr = [];
for (var i=0; i<firstArr.length; i++)
for (var j=0; j<secondArr.length; j++)
thirdArr.push(firstArr[i]+secondArr[j]);
var myThirdVariable = thirdArr.join(",");
You can use the plain old string split method to get 2 arrays.
http://www.w3schools.com/jsref/jsref_split.asp
You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string.
http://www.w3schools.com/jsref/jsref_join.asp
Try
var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'
var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)
function fn(fv, sv){
var fa = fv.split(','), sa = sv.split(','), ta = [];
for(var i = 0; i < fa.length; i++){
for(var j = 0; j < sa.length; j++){
ta.push(fa[i] + sa[j])
}
}
return ta.join(',')
}
Demo: Fiddle
OK so you don't need jquery to achieve this, just JavaScript.
check out this answer here to help you:
How to merge two arrays in Javascript and de-duplicate items

Why are property values "undefined"?

Javascript:
This is my example code below. I use prompt() variables to create string values for each loop.
var team = new Object;
team["fwd"] = "forwards";
for (i=1; i <2+1; i++){
var fwdName = prompt("enter player name");
team["fwd"]["p" + i] = fwdName;
}
It is my understanding with the above that in each loop, I get user input to read in a value for each new property (that is created by ["p"+i]) to be set to. The fwdName variable is overwritten with each loop.
I use the following to check that I actually put in values that can be used;
console.log(team.fwd.p1);
console.log(team.fwd.p2);
and I get undefined as output for each statement.
i belive the fwd property of your main object should be an object not a string.
team["fwd"] = {};

Categories