JavaScript. Dictionary Key is not a String? - javascript

Just a simple question. Having the next piece of code:
function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);
and having these results in the console:
380,95
undefined
Meet
I'd need to have in the second case also a 380,95. selection is supposed to be a string coming from the data object. Somehow when using this string like a dictionary key it's not working. How could I do then to get different values from types in some dynamic way like this?
Just to clarify, I'm not trying to get float numbers, what I need are two numbers separated by a ,

Javascript is case sensitive. Object has property meet whereas value of Selection is Meet. Hence, you will need to update your code to following
console.log(types[selection.toLowerCase()]);
For reference, String.toLowerCase()

Please check if
data.type === "Meet" // true
It should be "meet".
Btw. it is spelled meat, not meet.

Just to be clear
addMarker({'type':'meet'}) // would produce correct result
addMarker({'type':'Meet'}) // would produce result result you see
To correct this you could use lower Case String ,as provided by Nikhil
function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
selection = selection.toLowerCase();
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);
}
Or simply make proper call

Related

How to mix string with variables in an input needing mutiple values in js? (In this case, the coord attribute of the area tag)

So what the problem I have been facing so far is that I am currently trying to use javascript so that the coords attribute of my area tag is set according to some variables(what it is doesn't really matter). However, the coords require 4 inputs (x1,y1,x2,y2) and I have some values that I am not going to use the variable for. Which means that I have to mix string and variables in the input which I have no idea on how to do.
To give you a better sense on what I am doing, here is a summary:
var p = some random value
var q = some random value
var a1 = document.getElementById(areaID);
a1.setAttribute("coords", "0,0, p,q")
Of course this didn't work as the "" made it think that p,q are strings instead of variables. So I tried some other where it all failed(some desperate attempts).
a1.setAttribute("coords", 0,0,p,q);
a1.setAttribute("coords", "0,0," + p + "," + q);
document.getElementById(areaID).coords = 0,0, p,q;
const list = ["0","0", p,q];
a1.setAttribute("coords", list);
So does anyone know how could I possibly do this?
The second option you tried should work. In your example, is areaID a variable or the actual id of the element? If it is the latter, then you need to put it in quotes: document.getElementById("areaID")
var p = "val1"
var q = 23
var a1 = document.getElementById("areaID");
a1.setAttribute("coords", "0,0," + p + "," + q)
console.log(a1);
<div id="areaID"></div>

Why method setValue doesn't output same as Browser.msgBox?

Since I could not make .toFixed(2) to work I designed my own piece of code to add desired decimal digits after the "." by simple joining two strings with + sign.
While Browser.msgBox outputs the 2 strings joined correctly as "1.00",
it seems like getRange.setValue outputs only the first of the 2 strings as "1" :(
function myFunction() {
var ss_calc = SpreadsheetApp.openById("1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ");
var sheet_calc = ss_calc.getSheetByName("Calcs");
var ss_source = SpreadsheetApp.openById("1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ");
var sheet_source = ss_source.getSheetByName("Farmah");
var decDig = ""; var strDec = ""; var impVal = "";
impVal = sheet_source.getRange(12,7).getValue().toString();
if (JSON.stringify(impVal).indexOf(".")>-1)
{ if (JSON.stringify(impVal).split(".")[1].length < 2 )
{
if (JSON.stringify(impVal).split(".")[1].length < 1)
{
decDig = "00";
}
else
{
decDig = "0";
}
}
}
else
{
decDig = ".00";
}
var strDec = impVal.toString() + decDig.toString();
Browser.msgBox(JSON.stringify(impVal).indexOf(".")+ "\\n" +
impVal.toString()+ "\\n" +
decDig+ "\\n" +
strDec);
sheet_calc.getRange(1,1).setValue(strDec);
}
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
What am I missing?
Here are the links to google spreadsheets ( anyone with the link can edit :)
(above code has to be triggered manually by script editor in the first spreadsheet here under):
https://docs.google.com/spreadsheets/d/1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ/edit?usp=sharing
You want to put the value of 1.00 to a cell "A1".
If my understanding is correct, how about this modification? I think that the reason of your issue is that the value by putting by setValue() is converted to the number. By this, 1 is shown. In order to put the value as 1.00, I think that there are 3 patterns. Please select one of them for your situation.
Pattern 1:
In this pattern, from your question, the value is put as a string using setNumberFormat("#").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("#").setValue(strDec);
Pattern 2:
In this pattern, from your question, the format of cell is set using setNumberFormat("0.00").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("0.00").setValue(strDec);
Pattern 3:
In this pattern, from the script of your shared Spreadsheet, When decDig is ".00", the format is set.
From:
sheet_calc.getRange(x+6,c).setValue(strDec);
To:
var range = sheet_calc.getRange(x+6,c);
if (decDig) {
range.setNumberFormat("0.00").setValue(strDec); // or setNumberFormat("#")
} else {
range.setValue(strDec);
}
Reference:
setNumberFormat(numberFormat)
If I misunderstood your question and this was not the result you want, I apologize.
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
Google Sheets, as well as other spreadsheet apps, have an automatic data type assignation, so things that look as numbers are converted to Google Sheets number data type, etc.
You could prepend an ' to force that a value be treated as text or you could set the number format in such way that numbers are displayed with two decimals. The cell formatting could be applied in advance, i.e., by using the Google Sheets UI commands or you could use Apps Script to set the format for you.

Jquery convert object to string and slice

Via ajax-based script i get object:
for example:
item.TYP_PCON_START
which value is, for example 201212...
When i try to slice him, i get oject error...
How could i slice this object so, that for example i get 2012, or better set two last numbers on furst place and add dot, like:
12.2012
How could i do this? (i append this text as value of select list)
You need to slice the string property, not the object itself:
item.TYP_PCON_START.slice(-2) + '.' + item.TYP_PCON_START.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/
edit: In the case that your property is a number, you must convert it to a string before attempting to slice it:
var propertyAsString = item.TYP_PCON_START.toString();
propertyAsString.slice(-2) + '.' + propertyAsString.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/1/
var a = item.TYP_PCON_START,
a = a+"",
a = a.split("");
a.splice(2,0,".");
a = a.join("");
a = parseFloat(a);
console.log(a);

jQuery - Addition

I have an issue in doing a simple addition and save the value in a variable.
Basically I have the following code:
var accsen;
var lowsev = parseInt(accsen);
var hisev = parseInt(accsen) + parseInt(0.65);
console.log('Lowsev: ' + lowsev);
console.log('Hisev: ' + hisev + ' Type: ' + typeof(hisev));
console.log('Accsen: ' + accsen);
The variable accsen is being given a value from the database. Lowsev is being assigned the same value as accsen,while hisev is being assigned the value of accsen + 0.65.
However the issue I am having is that both lowsev and hisev are remaining 0. On doing console.log I get these values:
Lowsev: 0
Hisev: 0 Type: undefined
Accsen: 0.75
Can anyone tell me what I am doing wrong in the addition? Am I using the correct operators?
Sounds like you want to use parseFloat instead of parseInt.
"Lowsev is being assigned the same value as accsen" It's not, you're rounding it to an integer.
But parseInt() doesn't round properly. 0.75 comes out as 0, so it's working. Assuming you actually want to round these values try
var accsen;
var lowsev = Math.round(accsen);
var hisev = Math.round(accsen) + Math.round(0.65);
EDIT given the response
Your JS is treating accsen as a string, you need to convert to a number
var accsen = '0.75'; // as other people have noted this val in your code is missing.
var lowsev = parseFloat(accsen);
var hisev = parseFloat(accsen) + 0.65;

summing numbers stored in an array in JavaScript

I want to sum a list of numbers stored in a JavaScript object. The object is created and updated using this code:
var myscore = $('input[name="Points1"]').val();
scorelist = JSON.parse(localStorage.getItem(playerName + 'scorelist') || '[]');
scorelist.push(myscore);
localStorage.setItem(playerName + 'scorelist', JSON.stringify(scorelist));
$('div.scorecolumn', column).html("Score: <br>" + scorelist.join('<br>') + "<br>");
Basically I take whatever is in the column at the time, parse it, add myscore, stringify it, join each element with a <br> and write the list to the scorecolumn. The list of numbers is saved as an object. My goal is to sum up all the numbers in the object at any given time.
This script is inside of a function that passes in a bunch of parameters which is why some variables look undefined here.
Any help would be greatly appreciated! Thanks
UPDATE:
var nicTotalScore = nicScoreList.reduce(function(score, total) {
return total + score;
}, 0);
console.log(nicTotalScore); //12120
console.log(nicScoreList); //["12", "12"]
UPDATE:
If the score field is left blank when submitted, an empty string " " instead of a score. this is registering as a 0 when the reduce method goes through the array. This doesnt affect the total, but say, for example, i wanted to then find the average score, it throws it off. any ideas there? thanks
If you push() to scorelist, I'd be tempted to say it's likely an Array.
You could use reduce().
var total = scorelist.reduce(function(total, score) {
return total + +score;
}, 0);

Categories