Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Should you you use classes, prototypes etc in Angular JS? I learned Angular JS before I learned Javascript (bad idea). Now I've started to read some about OOP in javascript. I'm very confused at the moment.
I have an example. It's a service. It has some data from server and some input from user. It runs som logic and populate the object which is then viewed for the user.
Option 1. Just an object. I've removed most of the code so it's more a pseudo code. This is the way you see in most examples and tutorials.
angular.module('calculationServices', ['ngResource']).
factory('CalculationFactory', function(UnitsFactory){
var calculations = {
mainCalculation: function(sizes, pipe, temperature){
if(sizes === null || temperature === null){
return;
}
var rawness = pipe.rawness;
var mediaDensity = temperature.density;
var results = [],
nrOfSizes = sizes.length;
for(var i = 0;i<nrOfSizes;i++){
var flow = this.input.flow.valueInSIunit;
var velocitySiUnit = this.velocityFN(sizes[i].innerdiameter/1000,flow);
var pressureDropInSiUnit = this.pressureDropFN(velocitySiUnit,mediaDensity, frictionFactor, sizes[i].innerdiameter/1000);
results.push({
size:sizes[i].nominalsize
innerDiameter:sizes[i].innerdiameter,
velocity:{
siUnit:velocitySiUnit,
userUnit:velocityUserUnit
}
});
}
return results;
},
powerFN: function(flow, cp, density, deltaT){
var power = flow * cp * deltaT * density;
return power;
},
velocityFN: function(innerDiameter, flow){
var area = Math.PI * Math.pow((innerDiameter) * 0.5 ,2);
return flow / area;
},
input: { //Input is hooked up to my $scope
flow:{
valueInSIunit: 0.00075,
value:0.75,
unit: 'l/s'
}
},
};
return calculations;
})
})
Option 2 Or. should I use classes, instantiating, prototypes etc. Something like this:
factory('CalculationFactory', function(UnitsFactory){
function PipeCalculations(params){
this.flow = params.flow;
this.pipe = params.pipe;
this.sizes = params.sizes;
}
PipeCalculations.prototype.velocityFN = function(flow, innerDiameter){
var area = Math.PI * Math.pow((innerDiameter) * 0.5 ,2);
return flow / area;
}
PipeCalculations.prototype.createPipeCalculationObjects = function(sizes){
var results = [];
var nrOfSizes = sizes.length;
var velocitySiUnit = this.velocityFN(sizes[i].innerdiameter/1000,flow);
for(var i = 0;i<nrOfSizes;i++){
results.push({
size:sizes[i].nominalsize,
velocity:{
siUnit:velocitySiUnit
}
});
}
return results;
};
var pipeCalculations = new PipeCalculations({
flow: { //Should this be hooked up directly to my scope?
valueInSiUnit: 55,
valueInUserUnit: 0.75
},
pipe: 0, //Data feed from controller
sizes: 0
});
pipeCalculations.velocity = pipeCalculations.velocityFN(pipeCalculations.flow.valueInSiUnit, 25);
pipeCalculations.output = pipeCalculations.createPipeCalculationObjects(pipeCalculations.sizes);
return pipeCalculations;
})
Is there a clear right and wrong here? I did option one first. It was very easy and everything worked smoothly. But it didn't feel quite "OOP". However, option 2 is much harder for me because it's difficult to find decent examples. Also, with option one I can simply attach my scope to my model and everything is updated automatically. But how do i do it correctly with option 2? Should i instantiate from my controller?
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two buttons. One for a random movie flavor, ex. ['love', 'war', 'true']. I have this working. The problem, the second button is supposed to pick a random movie from the movie flavor that was picked. Ex. If "Love" is picked, the a new random would come from the Love List ['Noel', 'Titanic', 'Pearl Harbor']. Appreciate any help, thank you all ... ^ _ ^ ...
var movieFlavor = ['Love', 'War', 'True'];
var loveMovies = ['Titanic', 'Noel', 'Pearl Harbor',
]
var warMovies = ['PT-109', 'Firebase Gloria', 'Pearl Harbor',
]
var trueMovies = ['PT-109', 'Remember the Titians', 'Pearl Harbor',
]
function newRandomMovieFlavor() {
var randomFlavor = Math.floor(Math.random() * (movieFlavor.length));
document.getElementById('movieDisplay1').innerHTML = movieFlavor[randomFlavor];
}
function newRandomMovie() {
var randomMovie = Math.floor(Math.random() * (movieFlavor.length * randomFlavor));
document.getElementById('movieDisplay2').innerHTML = movieFlavor.length * randomFlavor[randomMovie];
}
With Math.floor(Math.random() * moviesByType.length) you can generate the random index within the range of array length.
I maintained a dictionary of movies with movie-type as a key.
When the button is clicked, we can read the movie-type attribute and then get the list from the dictionary by type and return a random element from that array.
const movieList = {
love: ['Love1', 'Love2', 'Love3'],
war: ['War1', 'War2', 'War3'],
true: ['True1', 'True2', 'True3']
};
const getRandomMovie = (e) => {
const type = e.target.getAttribute('movie-type');
let moviesByType = movieList[type] || [];
if(moviesByType.length) {
const randomIndex = Math.floor(Math.random() * moviesByType.length);
const movie = moviesByType[randomIndex];
console.log(`${type}: ${movie}`);
}
}
document.querySelectorAll('button').forEach(btn => btn.onclick=getRandomMovie);
<button movie-type="love">
Love
</button>
<button movie-type="war">
War
</button>
<button movie-type="true">
True
</button>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In trying to learn more about JavaScript (Google Apps Script flavor), I created an object structure that I think might be useful for a number of projects. My main goals for this little demonstration are:
learn the use objects (classes) and inheritance
minimize calls to the Spreadsheet Service by summoning a data table once per sheet
use the Named Ranges on the spreadsheet to access the data in the table
The code below seems successful, but surely can be improved. A couple of major questions are:
Is there a better way to accomplish the inheritance of methods and properties than this?
The Spreadsheet() function gets run for each of the Sheet objects, resulting in the environment structure having separate "ss" and "namedRangeList" properties in each of the Sheet objects. Is this normal and expected? Or is there a better approach to avoid this duplication? Or, is JavaScript just recording pointers to a single instance of these objects, so it really doesn't matter that they appear to be duplicated?
Because they are common to and the same for all of the Sheets, I had expected "ss" and "namedRangeList" to show up only at the Environment level and therefore available to the Sheets through inheritance rather than duplication.
What other changes or approaches would improve my fledgling use and understanding of classes and objects?
Here is a stripped down version of my code that preserves the essence of the structure but leaves out comments, error handling, and other functionality.
function Environment() {
this.title = 'Car & Driver';
this.ui = SpreadsheetApp.getUi();
this.dd = new Drivers();
this.cc = new Cars();
}
function Spreadsheet() {
this.ss = SpreadsheetApp.getActiveSpreadsheet();
this.namedRangeList = {};
var namedRanges = this.ss.getNamedRanges();
for (var i = 0; i < namedRanges.length; i++) {
var range = namedRanges[i].getRange();
this.namedRangeList[namedRanges[i].getName()] = {
sheet: range.getSheet().getSheetName(),
row: range.getRow(),
column: range.getColumn(),
rowCount: range.getNumRows(),
columnCount: range.getNumColumns(),
}
}
}
Spreadsheet.prototype = Object.create(Environment.prototype);
function Sheet() {
Spreadsheet.call(this);
this.sheet = this.ss.getSheetByName(this.sheetName);
this.data = this.sheet.getDataRange().getValues();
}
Sheet.prototype = Object.create(Spreadsheet.prototype);
function Cars() {
this.sheetName = 'Cars';
this.abbreviation = 'cc';
Sheet.call(this);
}
Cars.prototype = Object.create(Sheet.prototype);
function Drivers() {
this.sheetName = 'Drivers';
this.abbreviation = 'dd';
Sheet.call(this);
}
Drivers.prototype = Object.create(Sheet.prototype);
Sheet.prototype.idxOf = function(namedRange) {
return (this.namedRangeList[namedRange].rowCount == 1) ?
this.namedRangeList[namedRange].row - 1 :
this.namedRangeList[namedRange].column - 1;
}
function test_Environment() {
var env = new Environment();
env.ui.alert('The third driver is ' +
env.dd.data[3][env.dd.idxOf('ddFirst')] + ' ' + env.dd.data[3][env.dd.idxOf('ddLast')] + '.');
var tests = [
['dd', 2, 'ddLast' , 'Bailey' ],
['dd', 3, 'ddLicense' , 'pro' ],
['cc', 1, 'ccRadio' , 122.5 ],
['cc', 4, 'ccModel' , 'Corvette'],
];
tests.forEach(function(t) {
var v = env[t[0]].data[t[1]][env[t[0]].idxOf(t[2])];
Logger.log( (v == t[3]) + ': ' + (t[0] == 'dd' ? 'Driver ' : 'Car ') +
t[1] + ' ' + t[2].slice(2) + ' is ' + v );
});
env.ui.alert(env.title + ' is all done');
}
You can take a look at the mozilla page of JavaScript Objects.
Also there are a tons of questions in stack about this issue about inheritance in javascript.
Also as talked in the comments if you want someone to criticize your code take a look at Code Review
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
I'm new to javascript and I'm trying to create a dynamic list of quiz questions in business catalyst. With the way BC is set up you can use {tags} to place user-created information on a page.
That said I'm trying to generate a list of quiz questions based on user selected values. I have created an object, "Question", and placed the necessary properties with their values into the newly defined objects below.
In my code I am currently trying to:
1 - Define the Question object class
2 - Define the 15 possible quiz questions
3 - Write a for loop that will write each question based on a key value from the previous question.
The funciton/for loop I've written will ultimately do this:
Write question 1
if question1 key has a value of 'Yes' then write question 2
if question2 has a key value of 'Yes' then write question 3
etc etc until there are either no more yes's or question 15 has been written.
When I try to execute my code below I get the error 'Uncaught ReferenceError: question is not defined' Can someone help me understand what I'm doing wrong? Thank you for any and all help!
NOTE: TO SAVE SPACE I HAVE ONLY INCLUDED THREE QUESTION VARIABLES. IN MY ACTUAL CODE I HAVE DEFINED 15 QUESTION OBJECTS.
<script>
function Question (questionNumber, questionText, answerType, answerA, answerB, answerC, answerD, correctAnswer, visualRef, refKey, nextQ, qTextField, aTypeField, mcAField, mcBField, mcCField, mcDField, mcUserAnswer, tfUserAnswer, sRatings, sSAnswer, passFail) {
this.questionNumber = questionNumber;
this.questionText = questionText;
this.answerType = answerType;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.answerD = answerD;
this.true = "True";
this.false = "False";
this.correctAnswer = correctAnswer;
this.visualRef = visualRef;
this.refKey = refKey;
this.nextQ = nextQ;
this.qTextField = qTextField;
this.aTypeField = aTypeField;
this.mcAField = mcAField;
this.mcBField = mcBField;
this.mcCField = mcCField;
this.mcDField = mcDField;
this.mcUserAnswer = mcUserAnswer;
this.tfUserAnswer = tfUserAnswer;
this.sRatings = sRatings;
this.sSAnswer = sSAnswer;
this.passFail = passFail;
this.createQuestion = function() {
document.write("This is writing question " + this.questionNumber );
};
};
var question1 = new Question("1", "{tag_q-question_1}", "{tag_q-answer-type_1}", "{tag_q-text-answer_101}", "{tag_q-text-answer_102}", "{tag_q-text-answer_103}", "{tag_q-text-answer_104}", "{tag_q-multichoice-answer_1}{tag_q-t/f-answer_1}", "{tag_q-visual-reference_1}", "{tag_q-youtube_1}{tag_q-vimeo_1}{tag_q-image_1_value}", "{tag_q-next-question_1}", "CAT_Custom_13", "CAT_Custom_11", "CAT_Custom_14", "CAT_Custom_15", "CAT_Custom_16", "CAT_Custom_17", "CAT_Custom_7", "CAT_Custom_8", "CAT_Custom_9", "CAT_Custom_10", "CAT_Custom_12");
var question2 = new Question("2", "{tag_q-question_2}", "{tag_q-answer-type_2}", "{tag_q-text-answer_201}", "{tag_q-text-answer_202}", "{tag_q-text-answer_203}", "{tag_q-text-answer_204}", "{tag_q-multichoice-answer_2}{tag_q-t/f-answer_2}", "{tag_q-visual-reference_2}", "{tag_q-youtube_2}{tag_q-vimeo_2}{tag_q-image_2_value}", "{tag_q-next-question_2}", "CAT_Custom_19", "CAT_Custom_20", "CAT_Custom_22", "CAT_Custom_23", "CAT_Custom_24", "CAT_Custom_25", "CAT_Custom_21", "CAT_Custom_26", "CAT_Custom_27", "CAT_Custom_28", "CAT_Custom_29");
var question3 = new Question("3", "{tag_q-question_3}", "{tag_q-answer-type_3}", "{tag_q-text-answer_301}", "{tag_q-text-answer_302}", "{tag_q-text-answer_303}", "{tag_q-text-answer_304}", "{tag_q-multichoice-answer_3}{tag_q-t/f-answer_3}", "{tag_q-visual-reference_3}", "{tag_q-youtube_3}{tag_q-vimeo_3}{tag_q-image_3_value}", "{tag_q-next-question_3}", "CAT_Custom_30", "CAT_Custom_31", "CAT_Custom_33", "CAT_Custom_34", "CAT_Custom_35", "CAT_Custom_36", "CAT_Custom_32", "CAT_Custom_37", "CAT_Custom_38", "CAT_Custom_39", "CAT_Custom_40");
for (var i = 1; i <= 15; i++) {
if (question[i].prototype.nextQ === "Yes") {
question[i].createQuestion();
} else {
question1.createQuestion();
};
}
</script>
You have created 3 individual objects and you are trying to access them as an array however they are individuals not an array.
Try this
var question = new Array();
question[1] = new Question("1", "{tag_q-question_1}", "{tag_q-answer-type_1}", "{tag_q-text-answer_101}", "{tag_q-text-answer_102}", "{tag_q-text-answer_103}", "{tag_q-text-answer_104}", "{tag_q-multichoice-answer_1}{tag_q-t/f-answer_1}", "{tag_q-visual-reference_1}", "{tag_q-youtube_1}{tag_q-vimeo_1}{tag_q-image_1_value}", "{tag_q-next-question_1}", "CAT_Custom_13", "CAT_Custom_11", "CAT_Custom_14", "CAT_Custom_15", "CAT_Custom_16", "CAT_Custom_17", "CAT_Custom_7", "CAT_Custom_8", "CAT_Custom_9", "CAT_Custom_10", "CAT_Custom_12");
question[2] = new Question("2", "{tag_q-question_2}", "{tag_q-answer-type_2}", "{tag_q-text-answer_201}", "{tag_q-text-answer_202}", "{tag_q-text-answer_203}", "{tag_q-text-answer_204}", "{tag_q-multichoice-answer_2}{tag_q-t/f-answer_2}", "{tag_q-visual-reference_2}", "{tag_q-youtube_2}{tag_q-vimeo_2}{tag_q-image_2_value}", "{tag_q-next-question_2}", "CAT_Custom_19", "CAT_Custom_20", "CAT_Custom_22", "CAT_Custom_23", "CAT_Custom_24", "CAT_Custom_25", "CAT_Custom_21", "CAT_Custom_26", "CAT_Custom_27", "CAT_Custom_28", "CAT_Custom_29");
question[3] = new Question("3", "{tag_q-question_3}", "{tag_q-answer-type_3}", "{tag_q-text-answer_301}", "{tag_q-text-answer_302}", "{tag_q-text-answer_303}", "{tag_q-text-answer_304}", "{tag_q-multichoice-answer_3}{tag_q-t/f-answer_3}", "{tag_q-visual-reference_3}", "{tag_q-youtube_3}{tag_q-vimeo_3}{tag_q-image_3_value}", "{tag_q-next-question_3}", "CAT_Custom_30", "CAT_Custom_31", "CAT_Custom_33", "CAT_Custom_34", "CAT_Custom_35", "CAT_Custom_36", "CAT_Custom_32", "CAT_Custom_37", "CAT_Custom_38", "CAT_Custom_39", "CAT_Custom_40");
for (var i = 1; i <= 3; i++) {
if (question[i].nextQ === "Yes") {
question[i].createQuestion();
} else {
question[1].createQuestion();
};
}
I'm working in JavaScript and want to keep a list of set km/mph approximations to hand. (I can't convert programmatically, I'm working with an external API that expects certain values, so it really does have to be a dictionary equivalent.)
Currently I'm using an object:
var KM_MPH = { 10: 16, 12: 20, 15: 24 };
Going from mph to km is pretty easy:
var km = KM_MPH[10];
How do I find mph, given km? Also, is an object the best data structure to use for this sort of thing in JavaScript? I'm more used to Python.
A basic JavaScript object is in fact the best choice here. To find a reverse mapping, you can do:
function mphToKM(val){
for(var km in KM_MPH){
if(KM_MPH[km] === val){
return km;
}
}
return null;
}
Or, if you anticipate having to do a lot of lookups, I would recommend having a secondary JS Object that is the mirror of the first
var mph_km = {};
for(var km in KM_MPH){
mph_km[KM_MPH[km]] = km;
}
// mph_km[16] ==> 10
I don't know if you are in fact doing this for conversion between kilometres per hour to miles per hour... if so, it seems to make more sense to just do the conversion directly instead of relying on a hash mapping of the values.
var conversionRate = 1.609344; // kilometres per mile
function kphToMPH(val){
return val / conversionRate ;
}
function mphToKPH(val){
return val * conversionRate;
}
You can use iterate over all entries to find to find your key
Mostly a dict is used to from key=>value
Alternatively you can have two lists
var km = [];
var mph = [];
with their corresponding indices mapped
This is much closer to a Dictionary data structure, since you can have dozens of elements:
var dictionary = [
{ key: 10, value: 12 },
{ key: 12, value: 20 },
{ key: 15, value: 24 }
];
Then you can also use some JavaScript Framework like jQuery to filter elements:
var element = $.filter(dictionary, function() {
return $(this).attr("key") == 10;
});
alert($(element).attr("value"));
Yes, the JavaScript object is the correct choice.
Create a second object to do the reverse lookup:
var i, MPH_KM = {};
for(i in KM_MPH) MPH_KM[KM_MPH[i]] = i;
var mph = MPH_KM[16];
The dictionary equivalent structure for a javascript object would look like this:
var dictionary = { keys:[], values:[] };
Above structure is an equivalent of
Dictionary(Of Type, Type) **For VB.Net**
Dictionary<Type, Type>) **For C#.Net**
Hope this helps!