pushing variables to array returns undefined - javascript

SOLVED, Thank you! I needed to specify the index.
I am trying to push a set of variables into an array from user input.
Without using push it is working fine;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
document.write(appointmentArr.start);
document.write(appointmentArr.end);
however, when I try to push the variables it returns undefined;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr.start);
document.write(appointmentArr.end);
Can anyone explain why this is happening?
As far as I am aware I need to use push because I eventually want to create a new, populated index number every time the user inputs data, so any help is greatly appreciated.
Thanks in advance

You are accessing array.
So, the document.write part should be like this
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

Since appointmentArr is an array, you should fisrt take appointmentArr[0] to access the first element of the array.
After you push the value, the appointmentArr becomes, [{start:inputStart, end:inputEnd}]
Since, it is an array you cannot access object keys directly, you have to take specific index element and then can access them using appointmentArr[index]
var inputStart = 'inputStart';
var inputEnd = 'inputEnd';
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr[0].start + ' ');
document.write(appointmentArr[0].end);
Please run the above snippet

You re-assigned your variable as Object.
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
This code overwrite appointmentArr from Array [] to Object { start:inputStart, end:inputEnd }
And in the second code:
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
You modify appointmentArr from Array [] to Array [ {start:inputStart, end:inputEnd} ].
So, following code will work as you want.
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

Related

Getting last item in array using javascript

I'm trying to get the last item in a array using JavaScript.
But I'm always getting all items in the array.
So far, I've tried several methods. Here is my code:
var pathCoords = ['1','2','3','4','5'];
var sample1 = pathCoords[pathCoords.length -1];
var sample2 = pathCoords.slice(-1)[0];
console.log(sample1, sample2);
Maybe You can use splice method of array like this :
var sample = pathCoords.splice(pathCoords.length-1);

Copying an array produces strange results ('copying'==referencing)

EDIT: the problem I came across was that I did not know that js arrays are treated as objects and any as so are referenced not copied. If you were interested in simply reversing a js array you can use...reverse();
I thought I would be able to simply do the following in javascript
var originalArray = [1,2,3,5,8,13];
var originalArrayCOPY = originalArray;
console.log ("new copy = "+originalArrayCOPY);
for(var zyx = 0; zyx <6; zyx++){
var xyz = 5-zyx;
originalArray[zyx] = originalArrayCOPY[xyz];
}
console.log("original now "+originalArray);
console.log("copy ="+originalArrayCOPY);
But my results are so strange that I feel I must not understand javascript at all!!
new copy = 1,2,3,5,8,13
original now 13,8,5,5,8,13,
copy =13,8,5,5,8,13,
I can-t see why this wouldn-t work and I honestly am not sure why the COPY of the original array is changed at all.
If I could at least name the problem I could ask google, also if you tell me the name of the problem I will rename by SO question.
use this:
var originalArray = [1,2,3,5,8,13];
var originalArrayCOPY = originalArray.slice();
console.log ("new copy = "+originalArrayCOPY);
for(var zyx = 0; zyx <6; zyx++){
var xyz = 5-zyx;
originalArray[zyx] = originalArrayCOPY[xyz];
}
console.log("original now "+originalArray);
console.log("copy ="+originalArrayCOPY);
'=' copy references and slice() will produce a new copy of the array.
see : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

store the index based array

Hi I have use the following code snippet to create the array .
var rows = [];
rows["_id1"] = 1;
but in this case 1 did not insert into the array. Is there any other way to achieve this.
Screenshot:
Make it an object.
var rows = {};
rows["_id1"] = 1;
Or if you really want an array, you can have an array of objects
rows.push({"_id1": 1});

javascript message queue

I am using javascript to create a message queue, say for example I want to store the messages "hello" and "word" to user with id "123", I am using the following to set and retrieve them.
var messages = [];
var userId = 123;
messages[userId].push("hello");
messages[userId].push("word");
needless to say, this is not working, damn arrays! How can I make this work, keeping it as simple as possible?
Thanks in advance
You need an array ([]) for every user:
var messages = {};
var userId = 123;
messages[userId] = ["hello", "word"];
You can use push too:
var messages = {};
var userId = 123;
messages[userId] = [];
messages[userId].push("hello");
messages[userId].push("word");
messages[userId] does not exist.
You need to put an array there:
messages[userId] = [];
well, technically you could push elements as properties of an object, which you have created and then iterate thorugh its properties.

Global var in JavaScript

This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.

Categories