How do I add this to an array dynamically? - javascript

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.

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.

Javascript assigning array to element of another array

I have a list of unique ID's of a parent nodes children stored into childrenIDs.
var childrenIDs=["8b69b08e-d75e-6ef6-2cf4-275ff130cd74","42325602-9312-3565-b7dc-37383ca53c17", "2c91dcd6-7436-eff5-393e-cea8cbef338c"]
I then assign those IDs to the second element of another array
nodeArray[index].splice(0,1,childrenIDs);
When nodeArray[index][0] is entered into the console, the right output (containing all of the IDs) is printed. However, if I type childrenIDs.length = 0 to clear the first array, calling nodeArray[index][0] produces a null output. It seems as if nodeArr[index][0] is almost acting as a pointer to childrenIDs in the way that when childrenIDs is cleared, so is nodeArray[index][0].
I need to be able to reuse childrenIDs. Is there something wrong with how I am clearing the array and is there a way for me to preserve the data in nodeArray[index][0] after clearing childrenIDs?
Can you try using this statement?
nodeArray[index].splice(0,1,childrenIDs.slice(0));
Instead of assigning the array as child, you should assign a copy of it.
childrenIDs.slice(0)
Which would look like this:
nodeArray[index].splice(0,1,childrenIDs.slice(0));

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.

Can a DOM object be an index/key in Javascript array?

Would like to maintain a map/hash of DOM objects. Can they serve as key objects? If not, what are the alternatives, please? If there are better ways - kindly enlist them as well.
You can put anything as the key, but before actual use it is always converted to string, and that string is used as a key.
So, if you look at what domObject.toString() produces, you see it is not a good candidate. If all of your dom objects have an id, you could use that id.
If not, and you still desperately need a key based on DOM object, you probably could do with using, for example, _counter attribute with automatic counter in background putting new unique value in a DOM object if _counter is not yet present.
window already maintains all DOM objects as properties. Instead of putting your own keys for each 'DOM object' try to use window or document object and methods that uses index based on the layout of DOM tree.
No, because object keys are strings.
You'd have to "serialise" your objects by id or something, then perform a lookup later. Probably not worth it, depending on what your actual goal is here.
No, but you can set an attribute on the DOM element that contains a number, which you would have as the index in a numerically-indexed array.
Easiest is to set a data-attribute on the element instead.
Not exact. But I think you want something like below. You can do with jquery,
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types
Refer below link :
http://api.jquery.com/serializeArray/

How can I pop() the last element of 2 arrays in single call using className?

I have two DIV-elements, which are assigned an array called "stack" using data().
Both DIV-elements have a class of .trigger.
I now want to pop() the last element of both arrays like so:
$('.trigger').data("stack").pop()
However this only takes off the last element of the FIRST array, although
$('trigger').length
Returns 2.
Is there a way to remove the last element from both arrays in a single line?
You could do this:
$('.trigger').each(function() { $(this).data('stack').pop(); });
In general, jQuery functions that return a value (like ".data()" or ".css()" when passed just 1 string argument) only operate on the first element in the matched array. Thus when you want to do something like your deal, you use an explicit ".each()" to get at each element yourself.
You could use 'map' -
var arr = $('.trigger').map(function() {
return $(this).data("stack").pop()
})
Demo - http://jsfiddle.net/5gvAH/
As Pointy points out this solution works well if you need the values that were popped from each array. If you just want to pop off the values and don't need the returned values then Pointy's suggestion would be the best fit.

Categories