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.
Related
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.
Since I started using JQuery ive always wondering how does this operator work in JQuery
Example:
for(var i = 0;i<=4;i++)
{
document.getElementById("mydiv").innerText += i;//<- works as expected
}
//results will be 0,1,2,3,4
but if i use JQuery instead i dont know how to do it
for(var i = 0;i<=4;i++)
{
$("mydiv").text(+i)//<- NO!
$("mydiv").text+(i)//<- NO!
$("mydiv").+text(i)//<- JAJA COME ON!
$("mydiv").text(i)+//<- I guess that was stupid
}
This isn't possible like this. Unlike innerText, text() is a method, not a property.
Try:
$("mydiv").text($("mydiv").text() + i);
Or if you'd rather not make 2 references to $("mydiv") you can do:
$("mydiv").text(function(i,v){
return v + i;
});
You can't use such shorcuts for jQuery methods, it only works for native assignment operators. For jQuery .text(), use a callback:
$("#mydiv").text(function(index, oldtext) {
return oldtext + i;
});
This callback thing works for all jQuery property "assignments", be it .html, .val, .prop, .attr, .css, or .text.
You just need to work with jQuery here. Use the text method to extract the value, and then call it again to set the new value:
for(var i = 0;i<=4;i++)
{
var mydiv = $("mydiv"),
t = mydiv.text();
mydiv.text(t + i);
}
Like other answers point out, jQuery is just a framework and is subject to same syntactic rules as any JavaScript code.
While I see the advantage of passing in a function to .text(), I don't think it's a general purpose approach to solve your real problem : how to concatenate text when you use a function instead of a variable.
I'd favor the usage of Array.join() for efficient concatenation:
var textParts = [ $("mydiv").text() ];
for(var i = 0;i<=4;i++)
{
textParts[textParts.length] = i;
}
$("mydiv").text(textParts.join(',')) // result: '...,1,2,3,4'
If you prefer the function approach over a loop, you could also use Array.map().
AFAIK DOM functions are rather slow so it's more effective to do the concatenation first and then set the div node value.
jQuery is not a programming language but a library built upon javascript, so, the rules are exactly the same as those you have to follow using javascript, and javascript has not been designed to understand these kinds of structures.
Edit
Of course I mean o.m(+1) does not increment o.p while o.p++ and o.p+=1 does :
var o = {};
o.p = 1;
o.m = function () { return this.p; };
o.m(+1); // o.p equals 1
o.p++; // o.p equals 2
o.p+=1; // o.p equals 3
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']
So, I have a button whose value is concatenated from variables and strings:
$('#btn1').attr('value','question'+currid+'ans1').button('refresh');
This will return something like question5ans1, for example. Now, at the top of the javascript document, this value exists as a variable with a string associated, like this:
var question5ans1 = "Sydney";
The problem is that the button displays "question5ans1" instead of "Sydney". Is there any way to fix/change that?
Use eval to evaluate the string as var.
$('#btn1').attr('value', eval('question'+currid+'ans1')).button('refresh');
Instead of eval, a better solution is to have such var in a object like below,
var questions = {'question5ans1' : 'Sydney' };
and in the function,
$('#btn1').attr('value', questions['question'+currid+'ans1']).button('refresh');
If the variable is in the global scope, you can probably fetch it like this:
$("#btn1").val(window['question' + currid + 'ans1']);
You should attach these kinds of variables to an object as you cannot directly convert a string to a variable name. eval should not need to be used.
var q = {
question3ans1: "London",
question4ans1: "Tokyo",
question5ans1: "Sydney"
};
$('#btn1').attr('value', q['question' + currid + 'ans1'] ).button('refresh');
I want to create a new variable in javascript but it's name should made of a stale part and a variable one like this:
tab_counter = 1;
var editor + tab_counter = blabla
well i want the new variable name to be in this case editor1, is this possible?
You cannot create a stand-alone variable name that way (except as a global) (edit or except with eval()), but you can create an object property:
var tab_counter = 1;
var someObject = {};
someObject['editor' + tab_counter] = "bla bla";
You can create globals as "window" properties like that, but you probably shouldn't because global variables make kittens cry.
(Now, if you're really just indexing by an increasing counter, you might consider just using an array.)
edit also see #Birey's somewhat disturbing but completely correct observation that you can use "eval()" to do what you want.
It is possible
var tab_counter=1;
eval("var editor"+tab_counter+"='blah'")
alert(editor1);
eval("var editor"+tab_counter+1+";")
editor2='blahblah';
alert(editor2);
http://jsfiddle.net/5ZLYe/
You can do the eval method used by Birey or you can create a custom property of an object such as...
obj[editor + tab_counter] = blabla;
But it sounds like you're going about doing whatever you're doing in a particularly horrible way. If you just want to store multiple items which you can index into use an array...
var array = [];
array[0] = blabla;
array[1] = blabla2;
alert(array[0]); //shows value of blabla
alert(array[1]); //shows value of blabla2
It seems like you may want to consider using a Dictionary for something like this. This link which references this link describes your options there.