Javascript + and string return value from function? - javascript

This is a stupid noob issue that just pisses me off .. sorry.
This works: alert('hello');
This works: alert(getsomestring());
This works: alert('hello'+'goodbye')
So why doesn't this work: alert('hello'+getsomestring());
I tried these with no luck:
alert('hello'+getsomestring(););
alert('hello'+getsomestring().toString(););
thanks.
using it as follows:
<script language="JavaScript">
function getQueryString() {
var assoc = new Array();
var queryString = unescape(location.search.substring(1));
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
assoc[key[0]] = key[1];
}
return assoc;
}
</script>
<script language="JavaScript">
alert('?h='+getQueryString()["search"];);
//localSearchHighlight('?h='+getQueryString()["search"]);
);
</script>

Your code has syntax errors, in the second <script> block. It should read:
alert('?h='+getQueryString()["search"]);
There was a ; inside the function call parens.
You had an additional line with ); after your comment.
Other than that, it seems to work like you want it too.

Take a look in your browser's error console; alert('hello'+getsomestring();) is a syntax error due to the semicolon. Semicolons separate lines and shouldn't appear in expressions. Remove it, and the expressions will work (as you have it typed at first: alert('hello'+getsomestring());).

There are no associative arrays in JavaScript. Only objects map keys to values.
Replace var assoc = new Array(); with var assoc = new Object(); or the shorthand var assoc = {}; then it works.
Also there's an superflous ; in your alert:
alert('?h='+getQueryString()["search"];);
^ --------- SyntaxError: Unexpected token ;

Related

Remove quotes from new JavaScript array

I have a string with currency values. I add those values to a new array like so:
console logged number values
var xxc = 5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13;
var m = new Array(xxc);
For some reason, when the array is formed, it adds double quotes around my array and it breaks my array when trying to read it.
["5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13"]
I've tried to map the values in the array to remove the string using:
m.map(s => eval('null,' + s));
But that doesnt work. How would i remove the quotes in the array?
Your first line isn't well formed you need something like...
var xxc = [5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13];
You really don't need to reassign it.
var m = xxc;
You can check to see if it's in the correct format by logging to console.
console.log(m);
var xxc = [5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13];
var m = xxc;
console.log(m);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Try this:
var xxc = [] ;
xxc = JSON.parse ([5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13]);
console.log(JSON.strigify(xxc) ;
To test, try:
console.log(xxc[2]) ;
and you should get: 5748198.74.

How is page.trendDescriptions = {}; work in the given piece of code?

I got code from http://cektkp.com/twittermarquee/twitmarquee.js to use a twitter style ticker:
<script type=\"text/javascript\">
//<![CDATA[
var page={};
$(function() {new FrontPage().init()});
//]]>
</script>
I understand there is an anonymous javascript function which creates an instance of FrontPage class and init's it. And var page={}; is an object literal, but is it correct to define it here as first line of the script tag?
I found this in a JS tutorial, You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
Also, in my javascript file I have the following code:
Drupal.behaviors.stocksTicker = {
attach: function( context, settings ) {
page.trendDescriptions = {};
loadTrendDescriptions();
}
}
.
.
.
var processSummizeInternal = function (B) {
var J = page.trendDescriptions[page.query];
.
.
.
function loadTrendDescriptions() {
$("#trends a").each(function () {
var A = $(this);
var C = A.parent().find("em");
if (C.length) {
var B = A.text();
var D = C.text().replace(new RegExp(B.replace(/([^\w])/gi, "\\$1"), "gi"), "<strong>" + B + "</strong>");
var E = A.attr("title").length ? A.attr("title") : A.attr("name");page.trendDescriptions[E] = [B, D]
}
})
}
I'm not able to understand how is js accessing this variable page.? There is no other reference of page anywhere else in any other file.
Is it correct to define it here as first line of the script tag?
You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
This quotation does target constructs like
{init: function(){/* do something*/}}.init();
where really the statement begins with an object literal. Pretty odd? Yes, you would never use such code anyway. In your case,
var page = {};
the object literal is inside the assignment statement. No problems here, it's totally fine.
I'm not able to understand how is js accessing this variable page.?
Then it will automatically refer to a global variable. And you actually even have defined such one in your first snippet, and initialised it to an empty object. The external js you included then defined a trendDescriptions property on it and accessed it happily a few times.

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

JSON conversion issue

I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');

Using a Javascript Variable & Sending to JSON

I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup:
function content(cur){
var mycur = $H(cur);
var pars = "p="+mycur.toJSON();
new Ajax.Updater('my_box', 'test.php', {
parameters: pars
});
}
function update(){
if(window.location.hash.length > 0){
content(window.location.hash.substr(1)); // Everything after the '#'
}
}
var curHashVal = window.location.hash;
window.onload = function(){
setInterval(function(){
if(curHashVal != window.location.hash){
update();
curHashVal = window.location.hash;
}
},1);
}
But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of.
Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done.
Thanks for the help!
EDIT: As an end result, I'd like the URL (say product:3,confirmed:1) to be returned as {"product":3,"confirmed":1}
A typical implementation of toJSON() needs either an Array or an Object as the top-most element. Sonsomethig like this will probably work:
var pars = {p: myCur};
pars = pars.toJSON();
First of all native JSON support and the toJSONmethod is not available in all browsers. Older browsers like IE 6/7 or Firefox 2/3 do not support it. You should use a JSON library like json2 by Douglas Crockford. Second I would suggest to use the stringify method of the global JSON object instead of the toJSON function. In my tests
JSON.stringify("...")
works just fine.
If anyone is still looking for my answer, here's the solution!
function build_json(str){
var new_str = "{";
var cut = str.split(",");
for(var x=0; x < cut.length; x++){
if(x > 0){new_str = new_str+",";}
var s = cut[x].split(":");
new_str = new_str+"\""+s[0]+"\":\""+s[1]+"\"";
}
return new_str+"}";
}

Categories

Resources