I am currently writing a large amount of code, but I will keep it simple. I have a javascript array (possibly an object, still unsure exactly of the conventional naming), here is the initialization code:
var myArray = ["assignS" , ";" , "S"]
This is what I get as a console.log() from firebug on the element. There is too much code to post as it is assigned multiple values through many for loops. So this array (or object) is printed later as follows:
document.write("S -> " + myArray);
output:
S -> assignS,;,S
I do not want these commas in the result, it poses problems as some elements in the array may be commas themselves. I have ruled out the .join() method because of this, and am unsure how to proceed.
You ruled out the join method why, exactly? It takes a parameter, the separator, which you can then use to specify no separator:
myArray.join("");
I recommend reading up on the documentation for .join().
Also, I wouldn't recommend you use document.write, it has very few good applications.
The .join method on an array will by default concatenate all items with a comma, but it takes one argument to override this to be any other string to use as the glue - including an empty string.
myArray.join(''); // is "assignS;S"
var a=[1,2,3,4]
var result="";
for(i= a.length-1; i>=0;i--){
result=a[i]+result;
}
document.getElementById("demo").innerHTML=result;
Use this code:
document.write("S -> " + myArray.join(" "));
Related
I believe in javascript, arrays have a ".count" property. However, I believe that when writing Parse cloud code, effectively you cannot use this since .count is in a word, used by Parse (for queries).
(1) Is that correct, and is the reason I gave correctly stated or a shambles?
I believe (it seems to work) you can go ahead and use .length in Parse cloud code for the length of an array; but I'm confused "why" since javascript doco says .length
(2) Is that correct - if so why can it be done?
You inevitably use "underscore" library in Parse projects; in fact does that library offer a way to get the size/length/count of an array?
(3) Is there yet another way, using _ ?
I swear I have seen Parse cloud code using "size" (something or other like that) in relation to arrays;
(4) Is there an idiom using something like 'size' ?
Finally, indeed, considering this typical example of using _,
Parse.Cloud.afterSave("Employee", function(request)
{
var company = request.object.get("company");
var query = new Parse.Query("Employee");
query.equalTo("company", company);
query.include("company");
var justEmails = new Array();
query.each(function(employee)
{
var thatEmail = employee.get("email");
justEmails.push(thatEmail);
}
).then(function()
{
var kount = justEmails.length;
console.log(">>> count is " + kount );
justEmails = _.uniq(justEmails);
kount = justEmails.length;
console.log(">>> but count is now " + kount );
});
});
(5) is there a way to do that in "one line", saying something like _.uniq(justEmails).sizeOrWhateverTheHell();
Finally in summary,
(6) what then is the best and most sensible and most idimoatic way to get simply the length of an array, in javascript in the Parse cloud code milieu -- is it indeed .length?
There is no such thing as count. Arrays (and strings) have a .length property. Use it.
I have no idea what this is asking.
No, use .length.
See 3
_.uniq(whatever).length
See 1
It's just JavaScript.
You are correct and the best way to get the number of elements of an array in javascript (and in Parse cloud code) is to use array.length
Length is the property of the array, whereas size is a function that's defined in some javascript frameworks. Always use the length property to get the number of elements in an array.
I have a standard $scope.totals = $scope.totals = {storage:0, dailystorage:0}; and an angular.forEach that adds cam.storage to the $scope.totals.storage to give me the total storage.
I am using this to do that:
$scope.totals.storage = $scope.totals.storage+cam.storage;
The problem is that, say if two cam.storage are 21.09 and 15.82, it'll make $scope.totals.storage 21.0915.82 - basically adding them like strings instead of like math.
How do I make it an addition - not a joining?
Judging from what you've posted (verifying that $scope.totals is already a number), cam.storage is a string. You need to parse it to a number before adding it to the existing value:
$scope.totals.storage += parseFloat(cam.storage);
If they are concatenating instead of adding, it sounds like you need to parse them as decimals (You can also use toFixed(int) to limit the decimals as needed).
$scope.totals.storage = parseFloat($scope.totals.storage)+parseFloat(cam.storage);
My solution I use {{(a*1)+(b*1)}} It work.
I am making an ajax call and getting back result from array that looks like result = [one, two, three];
I need to convert this to an array and iterate it. Since my string has no quotes around values array isn't read correctly.
Here is my code, if you can please show me correct way to do it. Thanks.
xmlhttp.open("POST","SearchServlet", true);
xmlhttp.onreadystatechange =
function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
resultData = xmlhttp.responseText;
// resultData = [one, two, three];
// need to make valid array to iterate it
for (var i = 0; i < resultData.length; i++) {
console.log(resultData[i]);
}
}
};
Hi "user" and welcome to SO. Thanks for the code sample and well-formatted question :)
Since HTTP requests use strings (they don't send arrays), the best way to send your response is in JSON format. You can then easily parse the JSON string into an array.
http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/
JSON is a really easy to use (usually) way to send strings and dump them into arrays and vice versa.
There's ways to do it in Java (which I assume is the language for your server-side code) and PHP (which many people use also) and every other language.
For some reason I recall the Java ones being more difficult to use than they should be, but hopefully I'm mistaken. Either way, it's not too hard to learn and will bring your code-fu to the next level for sure.
A hack-y, not correct, ugly way to do it using your raw string is:
// Remove first and last bracket
var data = resultData.substr(1, resultData.length - 2);
// Split the array
data = data.split(", ");
...but please don't do it this way, this is for educational purposes only (at the risk of a downvote). Also I haven't tested it but you get the idea.
Again, the best way to do it is change your design to use JSON everywhere.
Ideally, you would use the JSON.parse function, but since one, two, and three are not quoted, you will have to do some work.
You can run through each of the items in your square brackets and put double quotes around them, then call JSON.parse. Alternatively, do as Steve suggests and rewrite your server's handler to respond with proper JSON.
If they were quoted, JSON.parse would work like this:
> JSON.parse('["one", "two", "three"]')
["one", "two", "three"]
Try this, its a little more complex, but it'll work:
resultData = xmlhttp.responseText;
resultData = resultData.substring(1, resultData.length-1);
var resultArray = resultData.split(',');
Though I don't know exactly why you can't output a valid JSON (with quoted strings in your array), this little and dirty function can parse your "almost-array" to a valid one, by putting quotes and removing spaces, this function returns a real array.
function validArray(str){
return str
.replace(/[\[\]']+/g,"")
.split(",")
.map(function(v){
return v.replace(/^\s\s*/g, '').replace(/\s\s*$/g, '');
});
}
The best solution is to avoid this kind of parsing and respond with valid JSON. This way, you could simply do a JSON.parse and easily obtain a JS object.
I am trying to get values from a data set. My function has to loop from 1 to 7
to get my opening hours for 7 days. what i need to do is:
Where openHours[i] the "i" stands for a number between 1 and 7. I would like to attach that number on the word "openHours" in order to create a new word ex. "openHours1"
What would be the best way to do that? The "alert(i);" is working fine and is generating numbers from 1 to 7. I just need to attach those numbers on the string.
So far i tried everything that can comes in my head but I don't use javascript often so i am kind of stuck.
Thanks for the help.
function hoursFunction()
{
var i =0;
alert("Hello");
for(i=1;i<8;i++)
{
alert(i);
alert(hoursForm.openHours[i].value);
}
}
EDIT: After your comment, it would appear you are trying to get the following variable:
alert(document.getElementById("openHours" + i).value);
However, I would strongly consider using jQuery (or another library) to handle this, and you could do the following:
$("#openHours" + i).val();
You can use the bracket notation to access properties - they're the same thing as indices in JavaScript.
alert(hoursForm[openHours + i].value);
I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).