Is there an easier method to concatenate variables using JavaScript? - javascript

I'm currently doing this:
var 1 = "http://www";
var 2 = ".google.";
var 3 = "com/";
then concatenating them together like this
var link = 1+2+3;
Is there an easier and more proficient way of doing this?

I don't know what would be much easier than simple concatenation like you show, but you could put them in an Array and join it together.
(I fixed your variable names to make them valid.)
var first = "http://www";
var second = ".google.";
var third = "com/";
var link = [first, second, third].join("");
Or you could use the .concat() method.
var link = first.concat(second, third);
But both of these are longer than your original so I don't know if that's what you want.

Related

Dynamic dictionary using Javascript from two sources

I'm new to JavaScript, and I think at this point I may have bit off more than I could chew. Essentially, I'm trying to make a dictionary (which will eventually be serialized to JSON, if that's relevant) that allows the user to define any number of entries and set both the key and value as they wish. I'm up for another implementation ideas, but this is how I've tried to solve it so far.
I have a button that calls the following code, which is mimicked exactly for newVariableDescription class. This creates the text input boxes on the web form.
var nameElement = document.createElement("input");
nameElement.type = "text";
nameElement.className = "newVariableName";
var nameDiv = document.createElement("div");
nameDiv.type = "div";
nameDiv.appendChild(nameElement);
var newVariableNamesDiv = document.getElementById("newVariableNamesDiv");
newVariableNamesDiv.appendChild(nameDiv);
var descriptionElement = document.createElement("input");
descriptionElement.type = "text";
descriptionElement.className = "newVariableDescription";
var descriptionDiv = document.createElement("div");
descriptionDiv.type = "div";
descriptionDiv.appendChild(descriptionElement);
var newVariableDescriptionsDiv = document.getElementById("newVariableDescriptionsDiv");
newVariableDescriptionsDiv.appendChild(descriptionDiv);
Now, this part works. I get all of the text boxes showing up just like I want, and can type into them. However, I can't figure out how to dynamically get access to this list AND pair them together.
This thread is very similar to what I want to do: dynamic dictionary using javascript
But I can't figure out how to get this code to do what I want:
var dictionary = {};
$('.newVariableName).each(function (index) {
dictionary['['+index+'].Key'] = $(this).val();
dictionary['['+index+'].Value'] = //access corresponding newVariableDescription here
});
I can obviously create a second loop with the other class (newVariableDescription), but that won't tie them together properly. I could store each of them in their own separate lists, and then combine those two lists into a dictionary, but I'm concerned about order remaining consistent and that's not an elegant solution.
Thanks in advance for any help.
If i understand right you want something like this with :eq selector
var dictionary = {};
$('.newVariableName').each(function (index) {
dictionary['['+index+'].Key'] = $(this).val();
dictionary['['+index+'].Value'] = $('.newVariableDescription:eq('+index+')').val();
});

How can I get the first element of this array in this var declaration?

If I do this with the element id 10_food_select:
var id = $(sel).attr("id").split("_");
I get an array like this:
["10", "food", "select"]
What I want is for id = 10 (or whatever the first element is). I can get this later by writing id[0], but how do I simply make id equal to the value of the first element of the split array, in that first var declaration?
[] is pretty much just like any other operator.
var id = $(sel).attr("id").split("_")[0];
Since everybody seems to be offering regular expressions now, here’s mine:
var id = +/[^_]*/.exec($(sel).prop("id"));
If it’s going to be a number, you can do this too:
var id = parseInt($(sel).prop("id"), 10);
I think that pretty much covers the useful one-liners.
Another way though
var id = +($(sel).attr("id").replace(/_.+$/,''));
You can do this:
var id = $(sel).attr("id").split("_")[0]; // returns 10
This will give you the proper id straight away, without even doing
var id = $(sel).attr("id").split("_"); // returns ["10", "food", "select"]
id = id[0]; // returns "10"
I think you are looking for this:
var id = $(sel).attr("id").split("_")[0];
Or you could use a regex replace if all you need is the first one from the split:
var id = sel.id.replace(/^([^_]+).*/, '$1')
Note: $(sel).attr('id') is not needed. sel.id is sufficient.

Javascript and dynamic variable insertion

Let's say I have am dynamically passing information to a variable in a URL like as shown below:
<script>
var ORDER = 200;
var QUANTITY = 1;
var EXTRA = [200,300,400];
var tag = document.write('<scr'+'ipt language="JavaScript" src="http://test.com/test/order.' + ORDER + '/quantity.' + QUANTITY"></scr' + 'ipt>');
</script>
Let's say I want to pass all the data in the EXTRA array... how would I do this?
I'm trying to get a URL that looks something like this after it is written to the page:
http://test.com/test/order.200/quantity.1/extra.200/extra.300/extra.400
(Passing the numbers to the same extra parameter in the URL is intentional, I need it to be passed in seperate instances but to the same variable)
I know I can use a for loop to cycle through the array.. how can I keep dynamically appending the numbers in the EXTRA array to the URL like in the example above?
Would something like this work?
for (i = 0; i < EXTRA.LENGTH; i++){
tag.append(EXTRA[i]);
}
Please advise if you can,
Thanks for your help!
This looks like a question about joining items in an Array. JavaScript has Array.prototype.join for this purpose, so you would want to do
var str = 'foo';
if (EXTRA.length) str += '/extra.' + EXTRA.join('/extra.');
str; // "foo/extra.200/extra.300/extra.400"

Variables inside JQuery selectors

This works...
var start = $('.nodes:first>span>div');
var foo1 = $(".nodes:first>span>div>div>div>div>span>div");
var foo2 = $(".nodes:first>span>div>div>div>div>span>div>div>div>div>span>div");
var foo3 = $(".nodes:first>span>div>div>div>div>span>div>div>div>div>span>div>div>div>div>span>div");
var foo4 = etc,etc...
Trying to consolidate to something like this...
var start = $('.nodes:first>span>div');
var separator = ">div>div>div>span>div";
var foo1 = $("start + 1*separator");
var foo2 = $("start + 2*separator");
var foo3 = $("start + 3*separator");
var foo4 = etc,etc...
Have been muddling for hours, but the syntax for this escapes me! Any pointers? Thanks!
The find() method seems like it should do it.
var $start = $('.nodes:first>span>div');
var separator = ">div>div>div>span>div";
var $foo1 = $start.find(separator);
var $foo2 = $foo1.find(separator); // etc...
If possible, I'd try and simplify your HTML so you don't need so many selectors though. This kind of code seems like it's going to be a nightmare to understand if you need to come back to it to fix something later.
Selectors are just strings so you just add strings to together and use them as a selector.
var start = '.nodes:first>span>div';
var separator = ">div>div>div>span>div";
var foo1 = $(start + separator);
var foo2 = $(start + separator + separator);
var foo3 = $(start + separator + separator + separator);
Though, if we understood what you were trying to accomplish, there is probably a much nicer way of doing it using less complication. For example, you should probably be using classes on the different types of divs and spans and then target specific classes without regard for how many intervening layers of divs there are. This makes your code much, much less brittle and much less tied to the exact HTML implementation (it still has some dependencies, but not near as many).
FYI, as far as I know, you can't multiply strings to get multiple copies of them so 2*str doesn't get you a string with two consecutive copies of str in it.

Parsing every element of an array as an integer

I have a string which I need to split into an array and then perform mathematical functions on each element of the array.
Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!
var stringBits = theString.split('/');
var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);
What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.
An easier method is to map to the Number object
result= stringBits.map(Number);
javascript 1.6. has map() ( https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map ), so you can do something like
intArray = someArray.map(function(e) { return parseInt(e) })
You can just loop through it:
for(var i = 0; i < stringBits.length; i++) {
stringBits[i] = parseInt(stringBits[i]);
}
["1","2"].map(Number)
result: [1,2]
If you add a plus (+) sign in front of your strings they should be converted to numeric.
For example, this will print 3:
var x = "1";
var y = "2";
alert((+x) + (+y));
But I am not sure if this is portable to all browsers.
Your code will become:
var stringBits = theString.split('/');
var result = (+stringBits[0]) + (+stringBits[3]) / (+stringBits[1]);
But this is just a hack, so use with care.
I think the parseInt states better what you are trying to do, but you should delegate this responsibility to another method that returns the final data that you need to process. Convert and then process, don’t convert while processing. Your code will be easier to read.

Categories

Resources