This is what i have so far. Basically every time i make a new Item object i need it to create a specific number of another object called Sensor. I've tried a few other methods and none seem to way the work that i need.
function Item (id,number,operator,numOfSensors){
this.id = id;
this.number = number;
this.operator = operator;
this.numOfSensors = numOfSensors;
var sensor = new Sensor[numOfSensors];
}
var Sensor = {
timeStamp:[],
itemPassed: function(){
timeStamp.push(Date.now());
}
}
Thanks so much for any help :) i'm a bit new to js
EDIT:
Hey guys! Thanks for the help. Basically my issue is neatly making an array of Objects. In the item object i want to make a [numOfSensors] amount of the Sensor object. I cant seem to find a way to do that. SO i guess my question is how would i go about creating an array of objects with a set number of elements?
Not sure when you really want to call itemPassed() and whether this is not rather a function of Item, but here is some code that might get you get started:
var Item = function (id, number, operator, numOfSensors) {
this.id = id;
this.number = number;
this.operator = operator;
this.numOfSensors = numOfSensors;
var sensorArray = [];
for (var i = 0; i<numOfSensors; i++) {
sensorArray.push(new Sensor());
}
}
var Sensor = function() {
this.timeStamps = [];
}
Sensor.prototype.itemPassed = function(){
this.timeStamps.push(Date.now());
}
See:
How to initialize an array's length in javascript?
http://code.tutsplus.com/tutorials/prototypes-in-javascript-what-you-need-to-know--net-24949
Related
I have an object with randomly generated data:
var obj = {
price: getRandomNumberRange(10, 200),
rooms: getRandomNumberRange(1, 5)
};
where
var getRandomNumberRange = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
I keep trying and failing to write a function, which will allow to create an array of 4 objects, so each objects' data will be regenerated at the time of creation. My function:
var createArr = function () {
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push(obj);
}
return arr;
};
In other words I expect to get this kind of array:
var arr = [{price:40, rooms:2}, {price:23, rooms:4}, {price:99, rooms:2}, {price:191, rooms:3}];
But I keep getting this:
var arr = [{price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}];
Will appreciate your help!
UPD. Thanks to everyone who suggested more complex way to solve my problem. As soon as I progress in JS I will recheck this thread again!
It looks like you reuse the object for pushing over and over and because of the same object, it pushes the same object reference with the latest values.
To overcome this, you need to create a new object for each loop and assign the random values with short hand properties.
// inside the loop
let price = getRandomNumberRange(10, 200),
rooms = getRandomNumberRange(1, 5);
array.push({ price, rooms }); // short hand properties
I am currently building a website like PCPartPicker but for watercooling parts for a school project. I dove in and I am having some issues. The most important on being this:
Here is my object constructor to start
var cpuCollection = [];
var myComputer = [];
function CPU(frequency,cores,socket,name) {
this.name = name;
this.frequency = frequency;
this.cores = cores;
this.socket = socket;
cpuCollection.push(this);
}
var i75930k = new CPU(3.6, 6, 2011.3, "i7 5930k");
var i54690k = new CPU(3.6, 4, 1150, "i5 4960k");`
After I built the object constructor I made some test objects using real computer parts.
In my HTML I have drop down menus that are populated by the objects on load using this code:
$(cpuCollection).each(function() {
$('#cpusel').append($("<option> " + this.name + "</option>"))
});
From there I wanted to make it so that when an option was selected in the dropdown the proper object would be pushed into the myCPU var for compatibility testing in another function. The code I used to accomplish this is as follows:
$('#cpusel').change(function() {
myCPU = new CPU();
$(cpuCollection).each(function(){
if(this.name = $('#cpusel :selected').text()) {
myCPU = this;
}
});
});
Unfortunately this code currently isn't working and is telling me that myCPU.socket is 1150 when the i75930k is selected when it really should be 2011.3. I am getting to wits end here and want to make some progress.
Thanks for the help in advance.
Edit: I fixed the equals sign issue and now I am thinking that the problem may be stemming from the way I push the objects into the cpuCollection array. When I try and log cpuCollection I get [CPU, CPU] which is obviously not what I want. How can I push the CPU objects on creation into cpuCollection with all of their properties intact.
Try this in your if() statement:
$('#cpusel').change(function() {
myCPU = new CPU();
$(cpuCollection).each(function(){
if(this.name === $('#cpusel :selected').text()) {
myCPU = this;
}
});
So, there were a few issues with some of your logic/syntax, and I will try to address them individually so you can better understand how I got a working solution:
1) You are pushing the element to an array from inside your object definition. This is typically bad practice, as it is not reusable, and will throw an error if an array called cpuCollection is not defined prior to the instantiation of that instance of the CPU object. It is better to say cpuCollection.push(new CPU(...));
2) When you append the options to the dropdown list, you should add the value property as well, so you can more easily grab the value in #3
3) If you set the value propery on the <option> elements, there is no need to look for the text of the selected option, you can simplify your selector to $('#cpusel').val()
4) There is no need to wrap your arrays in a jQuery object by saying $(cpuCollection).each(...), you can (and should) use the built-in vanilla javascript array operations.
5) I changed your .each() in the change handler to be a .some() this is because when you return true from .some() it stops any further iteration, which is what you want. Previously, it would continue to loop to the end, even if it already found the matching CPU.
6) I added a myCPU variable and instantiated it to null, so if you are running in strict mode, your change handler wouldn't throw an error for the variable not having been previously defined.
7) Your logic in your if statement was doing an assignment, rather than a comparison because you used = instead of == or ===, simple mistake.
Hope this helps!
var cpuCollection = [];
var myComputer = [];
var myCPU = null;
function CPU(frequency,cores,socket,name) {
this.name = name;
this.frequency = frequency;
this.cores = cores;
this.socket = socket;
}
cpuCollection.push(new CPU(3.6, 6, 2011.3, "i7 5930k"));
cpuCollection.push(new CPU(3.6, 4, 1150, "i5 4960k"));
cpuCollection.forEach(function(cpu, index) {
$('#cpusel').append($('<option value="'+ cpu.name + '">' + cpu.name + '</option>'))
});
$('#cpusel').change(function() {
myCPU = new CPU();
cpuCollection.some(function(cpu, index){
if(cpu.name === $('#cpusel').val()) {
myCPU = cpu;
return true;
}
});
console.log(myCPU);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cpusel"></select>
There is simple way(s) :
var cpuCollection = [];
var myComputer = [];
function CPU(frequency,cores,socket,name) {
cpuCollection.push({
name: name,
frequency: frequency,
cores: cores,
socket: socket
});
}
var i75930k = CPU(3.6, 6, 2011.3, "i7 5930k");
var i54690k = CPU(3.6, 4, 1150, "i5 4960k");
$(cpuCollection).each(function(i,cpu) {
var option = $('<option/>').html(cpu.name).data('cpu',cpu);
$('#cpusel').append(option);
});
$('#cpusel').change(function() {
var selected = $(this).find('option:selected');
var text = $(selected).text();
var myCPU;
// You can simply use : myCPU = $(selected).data("cpu")
console.log('via data:',$(selected).data("cpu"));
$(cpuCollection).each(function(i,cpu){
if($.trim(cpu.name) == $.trim(text)) {
myCPU = cpu;
// return false; ==> break the each();
}
});
console.log('via each:',myCPU);
});
See this demo.
I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.
I have "scene" with graphics "objects"...
Scene.prototype.objects=new Array();
Scene.prototype.add=function(obj){
var last=this.objects.length;
this.objects[last]=obj}
Scene.prototype.remove=function(obj){
this.objects.splice(obj.id,1)}
Scene.prototype.advance=function(){
for (var id in this.objects){
var obj=this.objects[id];
obj.id=id;
obj.advance();
}
}
Scene.prototype.paint=function(context){...}
each time creating and deleting many objects. Array.prototype.splice re-index array right? Does anyone know a better technique (adding and removing on javascript Array)?
In my opinion, is another possibility to do that something like
Scene.prototype.remove=function(obj){
delete this.objects[obj.id]; // don,t care about this.objects.length
delete obj; // not necessary...
}
I have not tried it yet...
I need a good book about JavaScript :)
Your delete method wouldn't work, because objects is an Array, and obj.id is the id of the object reference stored in an element in that Array. splice would be the method to use, but you'll have to know the index of the element in the Array. Maybe you should 'remeber' it this way:
Scene.prototype.add=function(obj){
var last=this.objects.length;
obj.objectsIndex = last;
this.objects[last]=obj
}
After which you can:
Scene.prototype.remove=function(obj){
this.objects.splice(obj.objectsIndex,1)};
//reindex the objects within the objects Array
for (var i=0; i<this.objects.length;i++){
this.objects[i].objectsIndex = i;
}
}
Note: Adding the objects Array to the prototype of your Scene constructor means it will be the same for all instances (static), is that what you want?
It seems you don't actually need an array for your objects. You can use another object has hash table:
(function() {
var i = 0;
Scene.prototype.objects = {};
Scene.prototype.add = function(obj) {
var id = i++;
this.objects[id] = obj;
obj.id = id;
};
Scene.prototype.remove = function(obj){
if(obj.id in this.objects) {
delete this.objects[obj.id];
}
};
Scene.prototype.advance=function(){
for (var id in this.objects){
var obj=this.objects[id];
obj.id=id;
obj.advance();
}
};
Scene.prototype.paint=function(context){...}
}());
I'd rather avoid using new Array() instead use [] (page 114 of book I mentioned in comment - 'JavaScript: The Good Parts' by Douglas Crockford ;)).
What's more, I don't think adding objects array to Scene prototype will work as you expect. You probably want to achieve some Object-Oriented structure, which requires some acrobatic skills in JavaScript, as it uses prototypal inheritance as it is class-free.
Try something like this:
var Scene = function(initial_objects) {
this.objects = initial_objects || [];
};
Scene.prototype.add = function(obj) {
this.objects.push(obj);
};
Scene.prototype.remove_by_index = function(index) {
this.objects.splice(index, 1);
};
Scene.prototype.remove = function(obj) {
var index = this.objects.indexOf(obj);
if (index > -1) {
this.objects.splice(index, 1);
}
};
Read also this: http://javascript.crockford.com/inheritance.html
var patientInfo = {}
patientInfo.patientID = row.patientID;
patientInfo.firstName = row.firstName;
patientInfo.lastName = row.lastName;
patientInfo.dateOfBirth = row.DateOfBirth;
patientInfo.age = row.age;
patientInfo.gender = row.gender;
When I print I patientInfo, I get only one row's data... how can I get all row's data?
Not quite sure what you mean. But assuming you are having this code in a loop, you are always overwriting the patientInfo data. Add them to an array:
infos = []
for(.....) {
var patientInfo = {}
patientInfo.patientID = row.patientID;
patientInfo.firstName = row.firstName;
patientInfo.lastName = row.lastName;
patientInfo.dateOfBirth = row.DateOfBirth;
patientInfo.age = row.age;
patientInfo.gender = row.gender;
infos.push(patientInfo)
}
It would be good to know here row is coming from. Maybe you could just do:
infos = []
for(.....) {
infos.push(row)
}
or maybe you don't have to do this at all. You have to provide more information.
More information => better answers.
To iterate over properties in an object, use for in.
for (var property in patientInfo) {
alert(property);
}
Keep in mind, however, that if someone has augmented Object, its enumerable properties will be iterated over too.
You can mitigate this by using hasOwnProperty().
for (var property in patientInfo) {
if ( ! patientInfo.hasOwnProperty(property)) {
continue;
}
alert(property);
}
Alternatively, you could specify you own toString() method which formats the values however you want. Be sure to return a string.