Literal Array can't be traverse by Jquery.each() - javascript

ok i do have this literal array declared as seen in a firebug screenshot below
now i tried to traverse it by using jquery.each();
this my code
$.each(window.feeditems,function(key,val){
alert('pass OK');
console.log('index:' + key + ', ' + 'value:' + val);
});
console.log('overview:' + window.feeditems);
console.log('length:' + window.feeditems.length);
ok so with the code above, the TODO inside the callback of $.each doesn't execute as expected the length is undefined when its printed it on the console.
well in a very strange case as i printed the window.feeditems in the firebug it displays my literal array completely like what displayed in the screenshot above.
now my question is how i can traverse this kind of array? i know jquery.each() relies on the length property of the array, and im also thinking of using for loop but how i can loop without knowing its size?
UPDATE 1
i recheck again the length and transfer it somewhere, it returns length zero, but put it with the next line the content checker code, it still contains the contents of the array.
UPDATE 2
Any possible workaround so I can traverse this array on the runtime without accessing the nodes manually in the code? for example using a for loop?

An array only accepts numeric indices. You appear to be defining string keys instead, which will not count as part of the .length or show up in a .each().
Instead of starting your definition with [], use {} to allow string keys. However, keep in mind that you still won't be able to use .length.

use JavaScript For...In Statement
http://www.w3schools.com/js/js_loop_for_in.asp
http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in

Related

Console.log: the length of array is 0 and 1 at same time

About the console.log, i believe i have a case related to
Javascript array length of 0
In my console i got
my code related at 24
const lists = this.props.localData.lists;
if(lists.length === 0 ) {
console.log('lists',lists);
}
What is going on here?
if it is right in its way, how could i access lists[0](undefined)?
could anyone give me a hint?
Thanks in advance.
Some of the comments hinted at the issue here, but I don't see one that fully and correctly explains it. Here is what happened.
The initial one-line display of the array is created at the time you call console.log(). Simply viewing the log doesn't change anything (contrary to what one or two comments say). And subsequent updates to the array don't change this one-line view either.
But when you click the little triangle to expand the log entry, the expanded multiline display is created using the current array contents at the time you click the triangle. That is what causes the difference between the two. Your array was empty when you called console.log(), and you added an element to it after that but before you clicked to expand the display in the console.
If you want to get a full view of the array as it exists at the moment of the console.log() call, a good way to do it is to use JSON.stringify(). You can use the third argument to this function to pretty-print the result. So in your example, you might use:
console.log( JSON.stringify( lists, null, 4 ) );
Check this out: foo = [] create a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.
foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.
Lucky with that.

Function param array, how to affect reference = [] or reference.concat(array2)? [duplicate]

This question already has an answer here:
Mutate JavaScript Array Inside Function
(1 answer)
Closed 8 years ago.
So it could just be I'm crazy tired but I can't seem to figure this out.
I've been picking up javascript which I'm finding horrible coming from actionscript 3 where everything was typed. I had a function that referenced two array variables directly, I later needed to use it again for a different data set so I've altered it to take parameters and now it's breaking.
I have one array full of elements, the 2nd is empty. When I call the function, a random element is removed from the first array and pushed into the 2nd array, that element is also returned by the function. If the 1st array is empty I have concat the 2nd array to fill it back up. The goal was to randomly iterate through the elements and not have the selected elements show up again until I had finished a full cycle.
Prior to concat I was using slice(which should work just as well?), the problem I believe is that I know have a parameter that is redefined when I do 'array = array2.slice()', concat doesn't seem to work around that. I don't know if returning the single sliced element from the first array is bad if I'm expecting a string, I think slice is returning an array with the single element, easy fix there though by adding [0] to the return statement.
Heres the code:
//Gets a random element from array, that element is moved from the 'src' array to the 'bin' array,
//this allows random selection without choosing the same element until all of 'src' array elements have been picked
function getRandomElement(array_src,array_bin){
//Randomly selects a tweet from the que, then stores it in another array so each tweet shows once before recycling
if(array_src.length==0 && array_bin.length>0) {array_src.concat(array_bin);} //Recycles array elements when the src array is empty
var randomElement = array_src.splice(Math.floor(Math.random()*array_src.length),1); //Grab a random array element
array_bin.push(randomElement);//array elements stored here to be recycled
return randomElement;
}
I think I could maybe use an object with two properties pointing to the arrays and pass those in, though it'd be nicer if there is a better way. I could also use push on array_src looping through the array_bin to work around that issue if there isn't any other way.
I wouldn't say this is a duplicate Felix. The answer you provided is pretty much the same, but the question itself is phrased differently, I wasn't aware of the term mutate, finding the question/answer wouldn't be easy, none of the suggested links SO provided were relevant. Worth keeping up for making the answer more discoverable to those unaware of the mutate term.
I have a hard time understanding the problem, but I think you are wondering why array_src.concat(array_bin) doesn't seem to do anything?
That's because .concat returns a new array. If you want to mutate the existing array_src array, you can use .push:
array_src.push.apply(array_src, array_bin);
FWIW, this has nothing to do with strong typing. JavaScript (and I guess ActionScript as well), is pass-by-value. That implies that assigning a new value to array_src doesn't change the value of the variable that was passed to getRandomElement.
But since arrays are mutable in JavaScript (and ActionScript I assume), you can mutate the array itself.

Using a for loop to populate an array with objects

I have a function that takes an array, consisting of 3 sets of strings. For each set of strings, the function should spit out 2 resulting integers/numbers.
Link to the jsfiddle of work in progress
So if the input is
["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]
I'm trying to get the function, by using a for-loop, to spit out 2 minute counts for each element of the array (a total of 6 minute counts, 2 per string).
I'm thinking I need the results stored in an object? Or maybe an array, consisting of objects? I'm a little bit confused here.
I'm confused as to how to organize it so that whatever is returned from the function, I can easily access it.
So maybe an array of 3 objects is returned is the best way to do it, with each object consisting of:
1st identifier key: an identifier of some sort (perhaps using the [i] from the for loop),
2nd key/property time1min: with the value being time1min (which is the 1st minute count),
3rd property time2min: with the value being time2min for that string.
As you can see from my jsfiddle above, I'm lost as to how to output to an object, or to an array of objects.
results is an array; so results[0].time1min
Try using console.log(results); instead. It plays nicer than alerts.

How do I add this to an array dynamically?

I'm storing div elements into an associative array, such that console will present such information to me. So console.log("enemyweakerpieces") gets me:
Object {left: null, top: div#silver.drag, right: null, bot: div#gold.drag}
So far, so good.
Then I attempt to add this into an array or processing later on.
pullablepieces[0] = neighbors['top'];
This works fine. Console.log pullablepieces[0] gets me..
[div#silver.drag]
With a large tree of useful elements below. Good, good.
But if I try to do the same thing dynamically...
pullablepieces += neighbors['top'];
I get instead "DIV HTML OBJECT" and pullablepieces array gets 23 length for adding just one div object. I can't iterate through each one of them, its like the object gets spread out instead into the array I can't refer to it correctly.
How should I code it so that it'll preserve the integrity of the object, and still just store it into a single array element?
Use the push method:
pullablepieces.push(neighbors['top']);
If pullablepieces is an array, you add elements to the end of an array with .push(), not with +=.
pullablepieces.push(neighbors['top']);
In javascript, += is a string or number operator so javascript will try to convert whatever you give it to one of those when you use that operator. It is not an operator that works on an array.

Does $.each not function on a json node if the node has only one child. Coffeescript

So I am trying to iterate through a json object, but I don't know if it will have one child or many. I am using the $.each jquery function with coffee script like so:
$.each data.searchresults.response.results.result, (i) ->
count = i + 1
console.log data.searchresults.response.result.address.street
Now this works if the "result" node has two instances; however, when it only has one instance it doesn't work. My question is, am I writing the $.each function in a sub optimal way and/or two should I just check how many result nodes exist then decide to either loop or just access the node?
JSON With Two: http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1dj9f5y35l7_agge7&address=3925%20edwardsville%20galena%20road&citystatezip=47122
JSON with One: http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1dj9f5y35l7_agge7&address=206%20Plum%20lake%20drive&citystatezip=47172
No error when running multiple result node, but here is the error when running it with only one result node:
TypeError: 'undefined' is not an object (evaluating 'data.searchresults.response.results.result[i].address.street')
So the issue I was having (stupid I know) was that inside the .each function I was using the full object path with [i] to access the correct iteration of the object.
So instead of using this console.log data.searchresults.response.result[i].address.street
I adjusted the script to look like this:
$.each data.searchresults.response.results.result, (i,result) ->
count = i + 1
console.log result.address.street

Categories