Possible to treat singular Javascript var as an array? - javascript

Whilst I am sure there's a duplicate question of this out there, because I am unfamiliar with javascript, I don't know the proper term, and thus wouldn't know where to start searching for it (if I knew what it was called, I'd just read up about it).
I have a singular var (that is not an array) that contains a set of numbers:
var Latitude = Math.floor(Math.random()*90) + Math.random();
I want to encode all numbers contained in Latitude, including the numbers after the floating point (and including the floating point, and any minus signs - although note this code example doesn't add a minus sign) into an array of letters, so 0 = A, 1 = B, so on.
Is there any simple way of converting the singular var into an array of individual numbers for encoding?

First, slight typo in your question, Math.random is a function. You want to convert the number you get to a string, the easiest way to do this is to add an empty string - ''. Then just use the split function to break the string into an array:
var Latitude = ((Math.floor(Math.random()*90) + Math.random()) + '').split('');

var latitude = new Array();
latitude.value = Math.floor(Math.random*90) + Math.random();
latitude.push(2);//demonstrating that it's an array;
console.log(latitude.value);//for testing purposes only
console.log(latitude);//for testing purposes only
Now you can use latitude's value but also use it as an array.
edit Sorry, I seem to have misread your question. Graham's answer is correct. But this might help someone with a similar problem. I thought you wanted to use the same variable to store a value and an array.

Convert the value first to string (toString()) and then split it (split()):
var arr = Latitude.toString().split('')

Related

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

Is using parseInt extraenous if unnecessary?

I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.
var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;
I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?
Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.

Should literal numbers not have quotes?

I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
That being said, is there anything wrong with quoting a literal number?
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
It isn't a number. Quoting a number makes it a string, which can make for some differences in the way they're handled. For example:
var a = 1;
var b = '33';
console.log(a + b === 34); // false
console.log(a + b === '34'); // true
Strings also have different types and methods for manipulating them. However, for most of the numeric operators (-, /, *, and other bitwise operators), they convert the string form to its numeric equivalent before performing the operation.
There are also a few differences where numbers are not stored with their exact value in some cases, due to the nature of the floating point format JavaScript numbers are stored in. Strings avoid this problem, though it is much harder to manipulate them. Converting these back to numbers reintroduces these issues. For example, see this:
var recordID = 9007199254740992;
var previousID = recordID;
recordID += 1;
console.log(recordID === previousID); // true
Adding quotes makes the number a string literal and so serves a different purpose than the Number literal defined without quotes.
JavaScript has the concept of type coercion which might have confused you.
Quoting makes a string of a number. It means that for example + operation will concatenate instead of add:
var a = 'asdf';
var b = '20';
var c = a + b; // asdf20
Here is a great explanation of what is going on.
I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
It's not a matter of required Vs not required (optional)
Using quotes (single or double) you state that it is a string (a sequence of characters - no matter if they're all digits)
If you don't place quotes you state it is a number.
That being said, is there anything wrong with quoting a literal number?
No if the entity it represents is not actually a number but a string. So...
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
If the number is a zipcode it may make sense to put quotes, because it is a "code", not a number and is not subject to arithmetics operations.
You're not going to divide a zipcode by 2 or sum two zipcodes because that would not make sense.
But instead of deciding to use quotes or not based on what the value represents I suggest you to consider the problem from the language perspective
You should understand and keep always in mind how do the language's operators behave when you use a string instead of a number in an expression (assignment or comparison).

JavaScript: Retrieve negative floating point number from string of mutiple sums

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:
500+50+36.5-45.2-10.
I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.
I have searched the use of regexp:
regular expression in javascript for negative floating point number result stored in array
Javascript Regular expression to allow negative double value?
but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?
Here is a snippet of my Js code:
For the full code, visit my fiddle.
totalInvoiced: function () {
var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;
});
I really like PhistucK's solution, but here an alternative with regex:
value1Arr = a.split(/(?=\+|\-)/);
This will split it, but keeps the delimiter, so the result will be:
["500", "+50", "+36.5", "-45.2", "-10"]
A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.
You can use this pattern that splits on + sign or before - sign:
var str = '500+50+36.5-45.2-10';
console.log(str.split(/\+|(?=-)/));

Finding an element in an array

4,5,6,7];
pin=3;
We got to search pin in hay.
Conventionally we loop through hay and check for pin( assume there is no native function called array.indexOf ).
How about,
hay=hay.join(",");
pin=","+pin+",";
index=hay.indexOf(pin);
Any Suggestions please?
Consider hay of [2,3,4] and a pin of 2... you'll be looking for ",2," in a string "2,3,4". Now you could add commas to the start and end of hay as well, but it's a bit ugly, isn't it?
There's then the problem of strings having variable lengths: consider an array of [1,222222,3,4]. When you look for 3, you'll end up with an inappropriate index because of the length of "222222". (Even in the case of only single digit values, you'll need to divide by 3.)
You've then potentially got problems when you start moving from integers to decimal values, which may be formatted differently in different cultures - possibly using a comma as the decimal separator. I don't know whether JavaScript uses the culture-specific separator by default, but that's part of the problem - you're suddenly having to consider aspects of the language/platform which have nothing to do with the task at hand.
Generally speaking, converting data into a string format in order to do something which doesn't really depend on the string format is a bad idea. It would be better to write a general-purpose indexOf method to perform the looping for you. (I'd be surprised if such a method didn't already exist, to be honest, but it's easy enough to write once and reuse if you need to.)
Heck, assume there is no string indexOf, either.
var A=[11,7,9,1,17,13,19,18,10,6,3,8,2,5,4,14,20,15,16,12],
L=A.length, n=3;
while(L>-1 && A[--L]!==n);
alert(L)
You don't need to use string in the middle, you can just loop through your array, if I understand your question right.
var hay = [1, 2, 3, 'Whoa', 'wheee', 5, 'needle'], needle = 'needle';
for ( var i = 0, len = hay.length; i < len; i += 1 ) {
if ( hay[ i ] === needle ) {
alert( "hay’s element number " + i + " is the needle!" );
break;
}
}

Categories

Resources