Declare and fill in the an array with the for loop - javascript

I want to create an array using a for loop in JavaScript. I want my array to be consisted of 10 variables or more (var kaunt1, var kaunt2, etc...) which will be actually numbers from div tags.
I tried this code below, but it isn't working??? Am I missing something?
var arr = [];
for(var i=1; i<=10; i++) {
var kaunt[i] = parseInt(document.getElementById("A"+i).innerHTML, 10);
}

var kaunt[i] = ... isn't how you add an index to an array, that's a syntax error.
Just use kaunt[i] = ....

You're declaring arr, but using kaunt? Not sure what that's about, but you should normalize that if they're meant to be the same thing.
Anyway, use kaunt.push(parseInt(document.getElementById("A"+i).innerHTML, 10)); (no var) inside your for.

Other's beat me I think, but this should do it...
var kaunt = new Array();
for(var i=1; i<=2; i++) {
kaunt[i] = parseInt(document.getElementById("A"+i).innerHTML, 10);
}

Get rid of the var in front of kaunt[i].
kaunt[i] = ....

Related

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

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Is this a valid array (value)?

var leaguetable = new Array();
leaguetable[0]= #leaguetable;
leaguetable[1]= #leaguetable1;
leaguetable[2]= #leaguetable2;
leaguetable[3]= #leaguetable3;
leaguetable[4]= #leaguetable4;
leaguetable[5]= #leaguetable5;
leaguetable[6]= #leaguetable6;
leaguetable[7]= #leaguetable7;
leaguetable[8]= #leaguetable8;
Can you have ID as the array values like I have done? Because this is not working for me at the moment.
You need to wrap your values inside quotes '#leaguetable1', '#leaguetable2'.....
However, you can just use a simple for loop to achieve it automatically instead of manually adding it:
var leaguetable = new Array();
leaguetable[0]= '#leaguetable';
for(var i=1; i<=8; i++) {
leaguetable[i] = '#leaguetable' + i;
}
console.log(leaguetable);
Fiddle Demo
Bo, #foo is not a valid JavaScript expression. You meant '#foo' instead.
Also, you can (should) use an array literal instead of new Array:
var leaguetable = [
'#leaguetable',
'#leaguetable7',
...
'#leaguetable8'
];

How to iterate over JSON data

The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?
for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}
You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.
You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.
Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".
There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.

How to "clean" an array in javascript?

I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']

Categories