Accessing a specific array - javascript

I have a set of arrays named in the following fashion: question0, question1, question2 etc.
I also have a variable that corresponds to the question number.
With this, how would I access array question0 without having to type out the whole name. For example, in a for loop, I have if the loop number is 5, I want to do an operation on question5. I know this is really simple, but I haven't been able to find the solution.

Variables ending in sequential numbers are usually a hint to use arrays. Sounds like you need an array of arrays instead, and then you can just:
doOperation(question[somenumber])

Why not just use a big array, question, where each item it itself an array?
That aside, if the variables are global then you could use window['question'+i], with i being the number of the question.

Don't use variable names with an ordinal number as their suffix; use the proper structures, such as an array:
var questions = ['why?', 'what?', 'where?'],
nr = 2; // the question number
alert(questions[nr]);
In my example, each "question" is a string, but it could be any other structure, including another array.

I think it would be simpler to have your question(n) values as an array. From there you could use the following: questions[i] where i represents the current loop number, thus improving manipulation.
var questions = [["What?", "Why?"], ["When?", "How?"]];
for(var i = 0; i < questions.length; i++) {
for(var j = 0; j < questions[i].length; j++) {
console.info(questions[i][j]);
}
}

Related

updating a JSON objects value with a for loop in Java Script

I have an array of 11 objects which contain JSON data. I wrote a function in which a new key with a zero value is added to each of the objects. Now I want to update the value of the said key in all 11 objects. The data is stored in an array2 with 11 numbers. My for loop doesn't seem to work for this, and the only way to do it (so far) is to hard code it. Does anyone has a suggestion how this can be done?
The desired outcome would be this:
array[0].new_key = array2[0];
array[1].new_key = array2[1];
The first art of the function, before the for loop with j, is for adding the new key into the original array and that part works.
for (i = 0; i < array.length; i++) {
array.map(i => i.new_key = 0);
console.log(array)
for (j = 0; j < array2.length; j++) {
array[i].new_key = array2[j];
console.log(array)
}
}
}```
I split it into two functions, I realized that I made it too complicated and it didn't made sense. I wrote a second function that only updates all the key values, so indeed, I removed the inner loop as it was not needed. Thank you for the help.
.map() does not modify the original array:
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
You will want to get the result of the map by assigning it to a variable, and see what is happening there. Right now you don't do anything with it, so it will just disappear.
While the above is true for maps, in this case the original array is being modified as we access the object's properties and modify them there.

for..in loop loops over non-numeric indexes “clean” and “remove”

This is something very basic I might be missing here but I haven't seen such result till now.
I have a for loop where options.headers.length is 3. And in for loop I am dynamically creating a table header. Ideally this loop should run three times for 0 1 and 2 but when I have printed index it's printing 0,1,2,clean and remove. I haven't seen clean and remove as indexes. I know this information is not sufficient enough but if you have any clue please suggest. something might be overriding this is all I am concluded too after my debugging.
for (index in options.headers)
if you don't want to iterate clean and remove then change the loop to:
for (var i=0; i< options.headers.length;i++){
//use i for getting the array data
}
if you use for (index in options.headers) it will iterate for non-numeric keys also.
don use just index (as that is = window.index = global = bad) use var index
(read more here https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=globals+javascript+bad)
you have to check does the array has it as own property or maybe its some function (more after answer)
for (var index in options.headers) {
if (options.headers.hasOwnProperty(index) {
// code here
}
}
more about #2:
let's say we have
var array = [0,1,2,3];
and besides that, extending array with function (arrays can have functions in javascript and strings too)
Array.prototype.sayHello = function() {
alert('Hello');
};
then your loop would print sayHello as part of the array, but that's not it's own property, only the arrays
I assume that options.headers is an Array?
This happens when you (or some framework you load) adds methods to the Array prototype. The "for in" loop will enumerate also these added methods. Hence you should do the loop for an array with:
for (var i = 0; i < options.headers.length; i++)
That way you will only get the real values instead of added methods.

How to write 'for-in' in JavaScript ? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Functional approach to basic array construction
I am new to js. I just want to know which one is the right approach. Below I have posted my code.
var doubles = (i*20 for (i in it));
var doubles ={i*20 for (i in it)};
Thanks
You should use ordinary for loops when iterating over arrays. for...in is used for iterating over object properties.
So, the correct way is:
for (var i = 0; i < array.length; ++i) {
// do something
}
To iterate over object properties:
for (var prop in obj) {
// do something with prop
}
Assuming it is an array, you can use .map():
var doubles = it.map(function(i){ return i*20; });
Also you might want to have a look at how to write List/Array comprehensions in JavaScript
Assuming you want to use Mozilla's Generator expressions (where it is an existing Iterator), you need to use square brackets:
var twentyfolds = [i*20 for (i in it)];
For future reference, ECMAScript 6 (aka Harmony) will most likely introduce a new sane way of iterating over objects (arrays included):
for(var x of array) {
// do something with x
}
It will also introduce array comprehensions and generator expressions to the core language:
var arr = [1, 2, 3];
console.log([i*20 for (i of arr)])
Both of these options are syntax errors. If 'it' is a list, then you can iterate through it with a for loop or the forEach method. In your case however, it looks like you are really looking for the map method.
var doubles = it.map(function (i) { return i * 20; });

Javascript object array comparison

I have two array of objects in javascripts. Like arr1[] = {emp1,emp2,emp3} where inturn emp1 has emp1.name and emp1.address as property.
Something like
arr1={object {name='a',address='b'} {name='c',address='d'} {name='e',address='f'} }.
arr2={object {name='a',address='b'}}.
I wanted to compare name property of two array objects and populate the missing items into another array. So result will be result[]={'c','e'}
Whats is the efficient way in achieving this? I don't expect code, please guide me in the right direction. Thanks.
The Array.filter method might be helpful. Check out more on it here.
the function could look like
function foo(arr1,arr2){
var arr3 = new Array();
var x=0;
for (var j =0; j<arr1.length; j++)
for(var i=0; i<arr2.length; i++)
if(arr1[j].name != arr2[i].name){
arr3[x]=arr1[i];
x++;
}
return(arr3);
}
This will loop through the 2 arrays and if the elements are not the same then they will be put in the third array. this is checking if any name in aarr1 is the same as in arr2. it doesn't check the other way.(ie if arr2 has an element that does not exist in arr1 it will not be put in arr3) but at least it should get you started.the function will accept the 2 arrays and return the third.

Javascript database rows in array - how to change value?

I have a database query that returns rows into a local array:
for (var i=0; i < results.rows.length; i++)
{
localResultsArray[i] = results.rows.item(i);
}
Later on, I want to update a value in the local array that corresponds to the 'answered_correctly' column in my database, but this value is not being updated. My code is:
localResultsArray[currentQuestionNumber].answered_correctly = 1;
but this doesn't change the value in the array to 1 for some reason - what am I doing wrong?
(Incidentally, if I do a comparison, eg. in an if statement then it works, so I must be using the wrong syntax above??)
if (localResultsArray[currentQuestionNumber].answered_correctly == 2)
{
incrementMe++;
}
Thanks in advance! Nick.
for (var i=0; i < results.rows.length; i++) {
localResultsArray[i] = results.rows.item(i);
}
As already pointed out, item() is unlikely to be a method, you probably meant item[i].
localResultsArray[currentQuestionNumber].answered_correctly = 1;
If localResultsArray[currentQuestionNumber] references an array, then the above line sets the answered_correctly property to 1. Is that what you want to do? It will not change the value in any array. You may want to do:
localResultsArray[answered_correctly] = 1;
or
localResultsArray[currentQuestionNumber] = 1;
depending on which of those variables references the column number.
Javascript arrays are just objects with a special length property (and some handy methods), the members of the array are just properties with numeric names (indexes or keys). So if you want to access the members of the array, use numeric property names. Using alphabetic names adds a new property that is not a member of the array.
From a quick review of your code, I'm wondering if the following line is corret:
localResultsArray[i] = results.rows.item(i);
I don't know what library you use that gives you the results object, but I highly doubt rows.item is a function and not an array...
Try
localResultsArray[i] = results.rows.item[i];
If it doesn't work, update your post with the library you used or some more data on the results object...

Categories

Resources