Passing an array to an object as an argument - javascript
I'm new to javascript and probably trying to do something stupid since an hour of googling didn't result in any examples.
I'm trying to learn objects so I made a constructor function like this:
//generic object
function clip(name, xposition, firstVisibleFrame, lastVisibleFrame, playStart, playEnd, defaultFrame, seqLoopStart, seqLoopEnd, backStateLevel){
this.name = name;
this.xposition = xposition;
this.outlinesArray =[];
this.firstVisibleFrame = firstVisibleFrame;
this.lastVisibleFrame = lastVisibleFrame;
this.outlinePath = ("outlines/" +this.name +"_");
this.playStart = playStart;
this.playEnd = playEnd;
this.defaultFrame = defaultFrame;
this.seqLoopStart = seqLoopStart;
this.seqLoopEnd = seqLoopEnd;
this.backStateLevel = backStateLevel;
};
Next I will create a new instance of that object with something like:
livingroomTable = new clip("livingroomTable");
...but now I'm really stuck because the next parameter I should pass to the function is actually a huge array with hundreds of values..
I tried to put the array inside the argument like this:
livingroomTable = new clip("livingroomTable", [value1, value2, value3, value4, value5 and so on and so on]);
but this gives me a syntax error.
I don't want to make this array a global variable either. What is the correct syntax of passing an array of values as a part of the function call's arguments?
EDIT:
Here is the actual code:
//generic object
function clip(name, xposition, firstVisibleFrame, lastVisibleFrame, playStart, playEnd, defaultFrame, seqLoopStart, seqLoopEnd, backStateLevel){
this.name = name; //objektin nimi tulee funktion kutsusta
this.xposition = xposition;
this.outlinesArray =[];
this.firstVisibleFrame = firstVisibleFrame;
this.lastVisibleFrame = lastVisibleFrame;
this.outlinePath = ("outlines/" +this.name +"_");
this.playStart = playStart;
this.playEnd = playEnd;
this.defaultFrame = defaultFrame;
this.seqLoopStart = seqLoopStart;
this.seqLoopEnd = seqLoopEnd;
this.backStateLevel = backStateLevel;
};
livingroomTable = new clip(
"livingroomTable", //name
["1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1220.69","1216.69","1207.69","1194.69","1167.69","1157.01","1147.24","1137.62","1127.74","1118.55","1109.88","1100.17","1090.51","1080.69","1070.28","1059.5","1048.87","1038.21","1027.6","1017.31","1007.31","997.208","987.153","977.152","967.848","959.258","950.808","942.887","935.103","927.326","919.256","910.834","902.452","894.231","886.561","879.269","872.072","865.057","858.292","851.484","844.527","837.655","830.747","823.629","815.898","807.221","798.142","789.152","780.341","771.358","762.248","753.089","743.97","734.954","726.148","717.699","709.299","700.826","692.102","682.849","673.258","663.37","653.188","642.48","631.498","620.551","609.866","599.544","589.439","579.088","568.508","557.794","547.028","536.037","524.912","514.043","502.899","491.412","480.102","469.097","457.844","446.368","434.919","423.84","412.74","401.657","390.55","379.284","368.162","357.316","346.606","335.973","325.144","314.01","302.658","291.207","279.392","267.133","254.62","241.775","229.179","216.763","204.423","192.239","180.41","168.484","155.502","141.701","127.828","114.008","100.403","87.0368","73.5946","59.7342","45.3524","31.0484","16.8761","helmi.96","-11.522","-25.6947","-39.5332","-53.1723","-66.7146","-80.253","-93.1294","-106.086","-119.531","-133.534","-148.801","-165.444","-183.67","-202.813","-222.634","-242.769","-263.074","-283.495","-303.787","-322.998","-341.376","-359.338","-377.081","-395.064","-413.628","-432.233","-451.409","-472.675","-493.827","-515.078","-537.029","-558.747","-583.8","-610.595","-645.864","-695.789","-711.965","-737.979","-752.979","-836.048","-862.75","-864.75","-884.835","-911.473","-927.473","-969.103","-1030.36","-1002.83","-1036.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08","-1048.08"];, //xposition
352, //firstVisibleFrame
545, //lastVisibleFrame
2058, //playStart
2304, //playEnd
2175, //defaultFrame
-1000, //seqLoopStart
-1000, //seqLoopEnd
1 //backStateLevel
);
Hmmmm actually I think my problem is the semicolon at the end of array right? :D
You're getting a SyntaxError because you have a ; semicolon at the end of the Array.
Remove that, and the error should go away.
["1220.69","1220.69", ..., "-1048.08","-1048.08","-1048.08"];, // <-- right here
It should look like this...
["1220.69","1220.69", ..., "-1048.08","-1048.08","-1048.08"], // <-- just a comma
You may want to consider using a code validator like JSHint.
There is nothing wrong with the principle that you are using.
You can put the array in a variable, and pass that to the function:
theArray = [1,2,3,4,5];
livingroomTable = new clip("livingroomTable", theArray);
Or you can use an array literal directly in the call:
livingroomTable = new clip("livingroomTable", [1,2,3,4,5]);
So, your constructor don't expect string and array parameters. You must call like that:
livingroomTable = new clip("livingroomTable", value1, value2, value3, value4, ...);
Related
How to convert arrays to objects in javascript?
How could I rewrite this code to object javascript. Since Array usage is prohibed, I can only use objects here. Insted of pushing values to array, I would like to push this values into objects. var container = []; document.addEventListener("submit", function(e){ e.preventDefault(); }); window.addEventListener("load",function(){ var submit = document.getElementsByClassName("btn-primary"); submit[0].addEventListener("click",add,false); document.getElementById("pobrisi").addEventListener("click",deleteAll,false); var dateElement = document.getElementById('datum'); dateElement.valueAsDate = new Date(); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10){ dd='0'+dd } if(mm<10){ mm='0'+mm } today = yyyy+'-'+mm+'-'+dd; dateElement.setAttribute("min",today); }); function add() { var title = document.getElementById("title").value; var type = document.getElementById("type").value; var datum = document.getElementById("datum").value.split("-"); datum = datum[2]+". "+datum[1]+". "+datum[0]; var data = new Book(title,type,datum); container.push(data.add()); display(); } function display(data) { var destination = document.getElementById("list"); var html = ""; for(var i =0;i <container.length; i++) { html +="<li>"+container[i]+"</li>"; } destination.innerHTML = html; } function deleteAll(){ container=[]; document.getElementById("list").innerHTML=""; } Wondering if is possible to write this code whitout any array usage.
initial remarks The problem here, in my estimation, is that you haven't learned the fundamentals of data abstraction yet. If you don't know how to implement an array, you probably shouldn't be depending on one quite yet. Objects and Arrays are so widespread because they're so commonly useful. However, if you don't know what a specific data type is affording you (ie, what convenience does it provide?), then it's probable you will be misusing the type If you take the code here but techniques like this weren't covered in your class, it will be obvious that you received help from an outside source. Assuming the teacher has a curriculum organized in a sane fashion, you should be able to solve problems based on the material you've already covered. Based on your code, it's evident you really have tried much, but why do you think that people here will come up with an answer that your teacher will accept? How are we supposed to know what you can use? a fun exercise nonetheless OK, so (we think) we need an Array, but let's pretend Arrays don't exist. If we could get this code working below, we might not exactly have an Array, but we'd have something that works like an array. Most importantly, if we could get this code working below, we'd know what it takes to make a data type that can hold a dynamic number of values. Only then can we begin to truly appreciate what Array is doing for us. // make a list let l = list(1) // (1) // push an item on the end l = push(l, 2) // (1 2) // push another item on the end l = push(l, 3) // (1 2 3) // display each item of the list listeach(l, function (x) { console.log(x) }) // should output // 1 // 2 // 3 runnable demo All we have to do is make that bit of code (above) work without using any arrays. I'll restrict myself even further and only use functions, if/else, and equality test ===. I see these things in your code, so I'm assuming it's OK for me to use them too. But am I supposed to believe your teacher would let you write code like this? It works, of course, but I don't think it brings you any closer to your answer var empty = function () {} function isEmpty (x) { return x === empty } function pair (x,y) { return function (p) { return p(x,y) } } function head (p) { return p(function (x,y) { return x }) } function tail (p) { return p(function (x,y) { return y }) } function push (l, x) { if (isEmpty(l)) return list(x) else return pair(head(l), push(tail(l), x)) } function list (x) { return pair(x, empty) } function listeach (l, f) { if (isEmpty(l)) return null else (f(head(l)), listeach(tail(l), f)) } // make a list let l = list(1) // (1) // push an item on the end l = push(l, 2) // (1 2) // push another item on the end l = push(l, 3) // (1 2 3) // display each item of the list listeach(l, function (x) { console.log(x) }) closing remarks It appears as tho you can use an Object in lieu of an Array. The accepted answer (at this time) shows a very narrow understanding of how an object could be used to solve your problem. After this contrived demonstration, are you confident that you are using Objects properly and effectively? Do you know how to implement an object? Could you fulfill this contract (below)? What I mean by that, is could you write the functions object, set, and get such that the following expressions evaluated to their expected result? In case it's not obvious, you're not allowed to use Object to make it happen. The whole point of the exercise is to make a new data type that you don't already have access to m = object() // m set(m, key, x) // m get(m, key) // x set(m, key2, y) // m get(m, key2) // y set(m, key3, set(object(), key4, z)) // m get(get(m, key3), key4) // z I'll leave this as an exercise for you and I strongly encourage you to do it. I think you will learn a lot in the process and develop a deep understanding and appreciation for what higher-level data types like Array or Object give to you
Since this is a homework I feel like I shouldn't solve it for you, but rather help you in the right direction. Like Slasher mentioned you can use objects With JavaScript object one book would look something like const book = { title: 'my awesome title', type: 'novel' }; book is the object title is a property with a value 'my awesome title' type is a property with a value 'novel' But objects can also have other objects as values. Something like const BookShelf= { Book1: { Title: 'my awesome title', Type: 'novel' }, Book2: { Title: 'my horrible title', Type: 'sci-fi' } }; You can reference the books in the bookshelf in two ways const book1 = BookShelf.Book1 // Returns the book1 object const title1 = Book1.Title; // Get the title const sametitle = BookShelf.Book1.Title // Returns title for book1, same as above. You can also use brackets: const book1 = BookShelf['Book1']; const title1 = BookShelf['Book1']['Title]; You can even make new properties on a object like this: const Book3 = { Title: 'running out of ideas' Type: 'memoir' }; BookShelf['Book3'] = Book3; Now the BookShelf has a Book3 property. So your BookShelf object looks like const BookShelf= { Book1: { Title: 'my awesome title', Type: 'novel' }, Book2: { Title: 'my horrible title', Type: 'sci-fi' }, Book3 = { Title: 'running out of ideas' Type: 'memoir' }; }; That should get you started :)
JavaScript Objects is a good way to go 1- define a new object: var myVar = {}; or var myVar = new Object(); 2- usage // insert a new value, it doesn't matter if the value is a string or int or even another object // set a new value myVar.myFirstValue="this is my first value"; // get existing value and do what ever you want with it var value = myVar.myFirstValue
How to concat buffers with delimiter in node.js?
I'm trying to concat two buffers with a space in between them in Node.js. Here is my code. var buff1 = new Buffer("Jumping"); var buff2 = new Buffer("Japang"); var buffSpace = new Buffer(1); buffSpace[0] = "32"; var newBuff = Buffer.concat([buff1, buffSpace, buff2], (buff1.length + buff2.length + buffSpace.length)); console.log(newBuff.toString()); As per official doc, the first argument will be the Array list of Buffer objects. Hence I've created buffSpace for space. Class Method: Buffer.concat(list[, totalLength]) list : Array List of Buffer objects to concat totalLength: Number Total length of the buffers when concatenated I'm getting the result as expected but not sure whether it is right way to do so. Please suggest if any better solution to achieve the same.
There are three changes I would suggest. First, if you are using Node v6, use Buffer.from() instead of new Buffer(), as the latter is deprecated. Second, you don't need to pass an argument for totalLength to Buffer.concat(), since it will be calculated automatically from the length of all of the buffers passed. While the docs note it will be faster to pass a total length, this will really only be true if you pass a constant value. What you are doing above is computing the length and then passing that, which is what the concat() function will do internally anyway. Finally, I would recommend putting this in a function that works like Array.prototype.join(), but for buffers. function joinBuffers(buffers, delimiter = ' ') { let d = Buffer.from(delimiter); return buffers.reduce((prev, b) => Buffer.concat([prev, d, b])); } And you can use it like this: let buf1 = Buffer.from('Foo'); let buf2 = Buffer.from('Bar'); let buf3 = Buffer.from('Baz'); let joined = joinBuffers([buf1, buf2, buf3]); console.log(joined.toString()); // Foo Bar Baz Or set a custom delimiter like this: let joined2 = joinBuffers([buf1, buf2, buf3], ' and '); console.log(joined2.toString()); // Foo and Bar and Baz
Read the Buffer stream and save it to file as: const data = []; req.on('data', stream => { data.push(stream); }); req.on('close', () => { const parsedData = Buffer.concat(data).toString('utf8'); fs.writeFileSync('./test.text', parsedData); });
Push a var in an array
Im fairly new to programming. Mostly I can find the solution to my problems online but not this time. I've found serveral posts about pushing a variable into an array, however when I console.log the array to check if the variable is actually in the array, he doesn't return the name of the variable that I want. What I get back is: [Card, Card], and what I want to see is: [card_Fireball, card_Waterbolt, etc]. The code I use is: var Deck = []; function Card(name, type, cost, points, damage, heal){ this.name = name; this.type = type; this.cost = cost; this.points = points; this.damage = damage; this.heal = heal; } var card_Fireball = new Card("Fireball", "spell", 2, 1, 3, 0); var card_Waterbolt = new Card("Waterbolt", "spell", 2, 1, 3, 0); Deck.push(card_Fireball); Deck.push(card_Waterbolt); console.log(Deck); The solution is probably fairly simple but I can't figure it out with my beginner experience :P Thanks for the help!!
You are doing everything correct just replace console.log with following: console.log(JSON.stringify(Deck));
Access the card names with "Deck[x].name", where x is the index of the card in the array Deck. To get all the names: for(i=0;i<Deck.length;i++){ console.log(Deck[i].name); } Assuming you name all your cards the same way as you did in your example, you could use this to get the variable names: for(i=0;i<Deck.length;i++){ console.log('card_' + Deck[i].name); }
If you want to get an array of the variable names you have used, those are lost on the way. In case you want an array of the names or any other property, try making a new array and pushing every value to it. var names = []; Deck.map(function(v) { names.push(v.name) }) console.log(names); Output: ["Fireball", "Waterbolt"]
How to setup arrays in my case
I need to create a array like the following var new = 'New'; var old = 'Old'; var posterArray = [new, old]; //I want to push posterType and posterYear into new and old array var posterType = [{'id':123, 'name':'test'}, {'id':456, 'name':'test'}]; var posterYear = [{'year':12345, 'status':'old'}, {'year': 3456, 'name':'old'}]; Is there anyway I can push posterType and posterYear into new and old variable inside the posterArray? For example, posterArray[0].push(postertype). Basically I need mullti-dimentional array and I am not sure how to accomplish here. Thanks for the help!
Seems like this would suffice your needs: var posterArray = { new: null, old: null }; Then later on: posterArray.new = [{'id':123, 'name':'test'}, {'id':456, 'name':'test'}]; posterArray.old = [{'year':12345, 'status':'old'}, {'year': 3456, 'name':'old'}]; And you can even do: var newObj = { id: 234, name: 'newtest' }; posterArray.new.push(newObj); EDIT Also heed ryanyuyu's warning: new is a reserved keyword in javascript
Fill observable-fields-object by same fields-names object
I have object that all of its fields are observable (knockout.observable). I have other regular object too, that its fields have the same names like the first-object-fields. I want to insert into each field of the first object, the value of the match-field at the second object. For example: var first = { a:ko.observable(), b:ko.observable() }; var second= { a:'my' b:'fields'; }; I want the first object to look like: first = { a:ko.observable('my'), b:ko.observable('fields') }; Yes, of course, I can do it by 'each' loop. But, my question is: Is there any build-in function that does it?
You can use the ko.mapping plugin: var results = ko.mapping.fromJS(second, first); See Documentation