I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.
Related
I am coding in node.js atm. I need to create a dynamic variable and invoke it.
e.g.:
username = 'im_a_user';
global['ws[' + username + ']'] = ws; //(yes, i want to store the connection with ws module)
but
ws[im_a_user].send('blabla');
doesn't work and node shuts down. So I want to know how global['ws[' + username + ']'] looks like for debbuging.
Do you know how I can print it - or even better, why im_a_user in ws[im_a_user].send('blabla'); isn't defined?
Thanks for your time!
Accessing object property is possible with brackets, but you have to give it a valid expression: a string literal or a variable. Looks like you are referencing a variable that is not defined. That's where Node chokes.
So try either with a variable that is defined
var key = 'im_a_user'
ws[key].send('blabla');
or a string literal
ws['im_a_user'].send('blabla');
I have a JavaScript object that looks like this:
var map = {
Monday: [
'something',
'something else',
],
};
When trying to access it, I noticed something strange I don't understand:
Doing console.log(map.Monday); returns undefined. To get the array back, I need to do console.log(map["Monday"]);.
Why is this? I already tinkered with quotes and uppercase/lowercase identifiers. The only time I encountered this so far was when there were numbers involved in the identifier (but of course it was still a string).
Edit
According to the comments it's working – indeed that is correct. Then the reason is probably related to the fact that the array identifier comes from an HTML select element:
$('.select').on('change', function(event) {
var selectedDay = $(event.currentTarget).val();
if (map.hasOwnProperty(selectedDay)) {
console.log(map[selectedDay]);
}
});
Then the reason is probably related to the fact that the array identifier comes from an HTML select element.
Yes… the syntax someObj.property is equivalent to someObj['property'], i.e. the property name is passed as a string in square brackets there.
Now if you want to dynamically access some property, and only have the property name as a string, then you need to use the square bracket syntax. For example:
var day = 'Monday';
console.log(map[day]);
The map[day] is equivalent to map['Monday'] which is equivalent to map.Monday. But if you were to call map.day, you would try to access map['day'], i.e. a property day in your object which obviously doesn’t exist.
What do we learn from this question? It’s a good idea to simplify the code in order to focus on the problem instead of including lots of irrelevant things. But when you do, you should make sure that the problem actually exists in the simpler code example. Because in this case, you eliminated the problem because you thought it doesn’t matter that you are trying to access the property dynamically.
In javascript both objects and arrays can be accessed as arrays and also as objects:
var a = []; //array
a["x"] = 100; //works
a.y = 50; //works
a.z = a.x + a["y"]; //works
var b = {}; //object
b.x = 10; //works
b["y"] = 20; //works
b["z"] = b["x"] + b.y; //works
If you still have a problem it's not related to the code you posted.
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']
How could I set a variable that I can read by using eval('productOptionTree' + '[0][1][0]')?
(the '[0][1][0]' part comes from another variable)
UPDATE
it's an ugly question, but I couldn't find another way to do it. the only answer I could find is:
newVal = 4;
dim = '[0][1][0]';
eval('productOptionTree'+dim+' = ' +newVal);
You don't need eval to read the item. Just do:
var x = productOptionTree[product[0]][product[1]][product[2]];
As you are free of eval, you can now easily use the same way to set the item:
productOptionTree[product[0]][product[1]][product[2]] = 42;
Is there any way to access split values without putting them into separate value?
var content = "some|content|of";
var temp = content.split("|");
var iwilluseit = "something" + temp[1] + temp[2]
How to do this w/o temp variable ?? (inline in setting of iwilluseit var)
It's incredibly inefficient, but you could call split multiple times:
var iwilluseit = 'something' + content.split('|')[1] + content.split('|')[2];
There's also the slice() + join() option:
var iwilluseit = 'something' + content.split('|').slice(1,2).join('');
Really, though, just creating the temp variable is the best way to go.
content.split("|").slice(1,3).join("")
No, you need to assign the result of Array.split() to an intermediate variable before it can be used, unless you don't mind the performance hit of calling Array.split() for each value you want to grab.
You could patch String.protoype to add a method that would take an array of strings and substitute it into a string.
How about:
var iwilluseit = "something" + content.split("|").slice(1,3).join(""));
You can also do:
var iwilluseit = "something" + content.substr( content.indexOf( "|" ) ).split("|").join("");
Of course, this will only work if you are simply trying to remove the first value.
More importantly:
Why do you need it to be in line?
If the purpose of not assigning it to a variable is to be able to do this in a context
where you can only have one Javascript expression, you could also use a closure, and
assign it to the variable in it:
(function() { var temp = content.split("|"); return "something" + temp[1] + temp[2]; })()
Which would be usable in an expression context, and not have the performance hit.