Angularjs for inside Controller running just once - javascript

I'm trying to store the ids of an array of objs, but appears that this for loop is running just once, very strange
for (var i = 0; i < softwareIds.length; i++) {
var b = softwareIds[i].id;
}
console.log(b);
console.log(softwareIds);
the last two lines of consoles returns this:
(number 2 is the first console.log returning the last obj id, and [Object, Object, Object] in the second console.log)
I'm using angujarJS, this for are inside a Controller, any idea?

You should declare the array first. see below
$scope.b = [];
for (var i = 0; i < softwareIds.length; i++) {
$scope.b.push(softwareIds[i].id);
}
console.log(b);
Your for loop is working fine but you are every time overwriting the value stored in the variable. You should push id value in an array.

Your loop is running three times. You keep updating the value of b.

The fact that you are using this code inside AngularJS controller doesn't have anything to do with what you are experiencing. This is a common thing, the console.log(b) line of code is going to be executed only when the for loop finishes its own thing and when the for loop is finished b variable is going to have the value of the last items id.
Also, in order to store the array of object ids as you need to use an Array, you pretty much answered on this question.
var ids = [];
for (var i = 0; i < softwareIds.length; i++) {
ids.push(softwareIds[i].id);
}

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.

JS arrays 3 deep getting lost

Learing JS by game. and of course the simplist is a clicker :-)
OK, so I have had lots of help with this, but the array section is just not sinking in. JS arrays do not work like arrays I am used to. two part question:
1. Why does the following code keep saying weaponlevelIfo[0] undefined, when it is defined? Please explain your answer, don't just correct mine LOL
2. I am more interesting in populating the code at runtime
As stated, all the research I am coming across as well as videos, talk about static data, i.e. it is put in at programing level, not run time.
I have had a really patient community person that has tried to help me understand JS arrays, but I must be blind as I am not seeing it. I can do in in other language just fine. but JS? nope.
// produces weaponLevelNfo[weaponId][level][cost] and [goldperclick]
// weapon, level 1-9, cost/goldperclick on each level
var weaponLevelNfo = new Array(14); // Outter array comprised of weapons 0-14
function initGame() {
for (let i=0; i <= weaponLevelNfo.length; i++) {
weaponLevelNfo[i] = new Array(9); // create leves array under weaponid array
for (let j = 0; j < weaponLevelNfo[i].length; j++) {
// loop through each 9 levels changing as needed
weaponLevelNfo[i][j] = new Array(2); // create an object for readability
}
}
}
initGame();// added - forgot to add this in the original post (sorry)
weaponLevelNfo[0][0][2]=3;
console.log(weaponLevelNfo[0][0][2]);
// always gives me weaponLevelNfo[0] not defined
I prefer the results to be as such
weaponLevelNfo[x][y].cost,
weaponLevelNfo[x][y].incomePerClick,
but am quite happy with
weaponLevelNfo[x][y][z],
weaponLevelNfo[x][y][z],
But as you can see from the code, assigning them direct or at runtime, I get the not defined error
What is missing to allow me to assign these at run time?
Two issues:
You need to call initGame to create all those subarrays, otherwise weaponLevelNfo[0] is not defined and so weaponLevelNfo[0][0] will trigger the error you get.
Your outer loop performs one iteration too many (<=). Change:
for (let i=0; i <= weaponLevelNfo.length; i++) {
by
for (let i=0; i < weaponLevelNfo.length; i++) {
Without that change, the last iteration is actually adding an element to the array in slot i, and so the length of the array increases... the loop becomes infinit.
Note that there are shorter ways to define such a nested array. For instance:
var weaponLevelNfo = Array.from({length:14}, () => Array.from({length:9}, () => [0, 0]));
When you create an array in javascript with new Array(2) this is an array with two positions. In this example (new Array(2)), you can access it at index 0 and index 1. Consider the following:
var newArr = new Array(2);
You can then access the two positions by the following:
var position1 = newArr[0];
var position2 = newArr[1];
So when you try this:
var position = newArr[2];
This will throw an undefined exception.
You can change the end of your example code to this:
weaponLevelNfo[0][0][1]=3;
console.log(weaponLevelNfo[0][0][1]);
You define array with two elements Array(2) with indexes 0 and 1 but you use index 2.
To initialize multidimensional array filled by zeros (if not remove .fill(0)) use
[...Array(14)].map(x=>[...Array(9)].map(y=>Array(2).fill(0)));
let a=[...Array(14)].map(x=>[...Array(9)].map(y=>Array(2).fill(0)));
a[13][8][1]=3;
console.log('Last element value:',a[13][8][1]);
console.log(JSON.stringify(a));

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.

Can't use window object until an alert has been sent in JavaScript?

Encountering a slightly weird problem.
I have an array containing ~100 items, each of which is to be an array of its own name. In order to use the variable as the array name, I've been using the window[VARIABLE_NAME] approach.
Eg, this is how I initialize them:
for (var i = 0; i < array_list.length; i++) {
window[array_list[i]] = new Array();
}
I add data to the arrays and perform some other operations, and at the end I want to sort each array, using a simple custom sort function:
for (var i = 0; i < array_list.length; i++) {
var array_name = array_list[i];
window[array_name].sort(function(a,b) {
return a[0] - b[0];
});
}
The problem I'm encountering is that, unless I can do an alert() before this for loop, the sort never occurs.
Is there a better approach to this, or do I need to initialize the window object somehow?
All of this is executing within the jQuery $(document).ready() function as it is...

Looping through an array of JSON objects in Javascript

I orginally was going to ask a question on why it wasn't working. But as I commented the code I realized that I could access the text array style and item was giving me the index. It took me a while to find this as the solution, however I would have much rather used item.text in the for loop. Is this [my posted answer] the valid way to loop through JSON objects in Javascript?
There's no such thing as a JSON object - once you've parsed your JSON (which is a string) you end up with simply an object. Or an array.
Anyway, to loop through an array of objects, use a traditional for loop. A for..in loop may work, but is not recommended because it may loop through non-numeric properties (if somebody has been messing with the built-in array).
In your specific case, if obj.body.items is an array then do this:
for (var i = 0; i < obj.body.items.length; i++) {
// obj.body.items[i] is current item
console.log(obj.body.items[i].text);
}
You can also, arguably, make the code a bit neater by keeping a reference directly to the array rather than accessing it via the whole obj.body. chain every time:
var items = obj.body.items;
for (var i = 0; i < items.length; i++) {
console.log(items[i].text);
}
"I would have much rather used item.text in the for loop"
In your answer - which really should've been posted as part of the question - because you are using a for..in loop your item variable is being set to each index in turn as a string, e.g., on the first iteration it will be the string "0", and strings don't have a text property so item.text doesn't work - although it should give you undefined, not null. But you can do this:
var item;
for (var i = 0; i < obj.body.items.length; i++) {
item = obj.body.items[i] // get current item
console.log(item.text); // use current item
}
That is, declare a variable called item that you set to reference the current array item at the beginning of each loop iteration.
<script type="text/javascript">
...
obj = JSON.parse(xmlhttp.responseText);
// displays the object as expected
console.log(obj);
// display the string next as expected
console.log(obj.body.next);
// displays the text of the item as expected
console.log(obj.body.items[0].text);
for (var item in obj.body.items) {
// displays the index value of the item
console.log(item);
// displays null - WHAT?? HUH?
console.log(item.text);
// displays the text - finally
console.log(obj.body.items[item].text);
}
<script>

Categories

Resources