Unexpected token operator «=», expected punc «,» - javascript

i am getting the following error
Parse error: Unexpected token operator «=», expected punc «,» Line
159, column 26
This is my code
function fitBounds(type="all", shape=null) {
var bounds = new google.maps.LatLngBounds();
if ( type == "all" ){
if ((circles.length > 0) | (polygons.length > 0)){
$.each(circles, function(index, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(index, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type == "single") && (shape != null) ) {
if (shape.type == google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (bounds.isEmpty() != true)
{
map.fitBounds(bounds);
}
}

You are trying to use Default parameters, which are a bleeding edge feature of JavaScript with limited support.
JS Lint rejects them unless you turn on the ES6 option.

#Quentin is exactly right: You need the es6 option.
There's lots more that fails JSLint, however, particularly your use of ==, which is a "coercing operator" -- check JSLint on equality -- and the bitwise option in the jslint section (there's no link directly to jslint directives, I don't think, so I linked just above it). As #AxelH suggests, there's likely more you really want to ask us. ;^)
Here's a version that lints on JSLint.com as it stands today. Note the /*jslint directive line at the top that includes the es6 tag:
/*jslint es6, white, browser */
/*global google, $ */
// These weren't declared, so I'm assuming they're
// within scope in your snippet's context.
// I put others that felt like globals (google, $)
// into globals, above.
var marker_index;
var markers;
var circles;
var polygons;
var map;
function fitBounds(type="all", shape=null) {
var bounds = new google.maps.LatLngBounds();
if ( type === "all" ){
// not sure why you're using bitwise `|` here.
// I think this'll be equivalent, though you should
// be able to set `bitwise` as an option if it's not.
// Still, you're evaluating to booleans, so `|` doesn't
// seem appropriate here.
if ((circles.length > 0) || (polygons.length > 0)){
$.each(circles, function(ignore, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(ignore, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type === "single") && (shape !== null) ) {
if (shape.type === google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (!bounds.isEmpty())
{
map.fitBounds(bounds);
}
}

#Quentin is right with his answer. You get syntax error due to reasons that he mentioned. What I can add to it is that you might try to drop EC6 syntax, and rewrite your function to old good JS.
// change from
function fitBounds(type="all", shape=null)
// change to
function fitBounds(type="all", shape)

A workaround to this issue could be this:
function fitBounds(type, shape_aux) {
var bounds = new google.maps.LatLngBounds();
if(typeof type === "undefined") {
type = "all";
}
if(typeof shape_aux !== undefined) {
shape = shape_aux;
} else {
shape = null;
}
if ( type == "all" ){
if ((circles.length > 0) | (polygons.length > 0)){
$.each(circles, function(index, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(index, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type == "single") && (shape != null) ) {
if (shape.type == google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (bounds.isEmpty() != true)
{
map.fitBounds(bounds);
}
}

Related

Automatically switch basemap at zoomlevel?

I am trying to make leaflet change the basemap depending on the zoomlevel. What I am trying:
(I am new to coding)
I am receiving an error statement:
SyntaxError: missing ) after argument list
I did check the syntax several time but cant find the error.
I also wonder if there is a more elegant way to write it, instead of that double if-else statement.
map.addEventListener("zoomend", changeBasemap);
function changeBasemap() {
var zoomLevel = map.getZoom();
if (zoomLevel < 5) {
if (map.hasLayer(osm)) {
map.removeLayer(osm);
stamen_Watercolor.addTo(map);
} else {
console.log(no need to change basemap)
}
} else {
if (map.hasLayer(stamen_Watercolor)) {
map.removeLayer(stamen_Watercolor);
osm.addTo(map);
} else {
console.log(no need to change basemap);
}
}
}
The error is because you forgot quotes in:
console.log(no need to change basemap);
Correct it to:
console.log("no need to change basemap");
Here's a suggestion about how your code could look cleaner:
function changeBasemap()
{
if ( map.getZoom() < 5 && map.hasLayer(osm) ) {
map.removeLayer(osm);
stamen_Watercolor.addTo(map);
return;
}
if ( map.getZoom() > 4 && map.hasLayer(stamen_Watercolor) ) {
map.removeLayer(stamen_Watercolor);
osm.addTo(map);
return;
}
console.log("no need to change basemap");
}

Having problems with Javascript Else If statement in Node Red

I have been fighting this problem all day. Heres a snippet of my code, 5 lines down in the else if is where things get screwy. I am also new to Javascript so that may be the reason I am unable to spot the mistake, but from what I have seen elsewhere, this code should work. Also the comments on lines 5 and 6 are swapped.
if (msg.payload.License_Plate !== null) {
// This portion checks for a valid number plate
if (readlpr == dblpr); { // we have a direct match, open the gate
opengate = 1; // will send open signal to gpio
} else if(readlpr !== null); { // from here on, we are checking for a partial plate match
validdigits = 0; // make sure we have data before continuing, as may be a rfid match
{
if (!context.count); { // check to see if counter already used, if not initialise it
context.count = 0;
Image of error message
You have a few errors:
if (readlpr == dblpr); {
...
} else if(readlpr !== null); {
...
if (!context.count); {
And also an extra opening-brace.
These shouldn't have a semi colon on the end:
if (readlpr == dblpr) {
...
} else if(readlpr !== null) {
...
if (!context.count) {
In the end it should look something like this:
if (msg.payload.License_Plate !== null) {
if (readlpr == dblpr) {
opengate = 1;
} else if(readlpr !== null) {
validdigits = 0;
// { <!-- Remove this as well, it's an extra brace
if (!context.count) {
context.count = 0;

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

JavaScript files.length not working in ie9 need alternative approach

I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.
I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.
I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API

How to detect if browser supports HTML5 Local Storage

The following code alerts ls exist in IE7:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?
Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.
You don't have to use modernizr, but you can use their method to detect if localStorage is supported
modernizr at github
test for localStorage
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
});
updated with current source code
if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
This function works fine:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Source: www.diveintohtml5.info
Also I don't want to use Modernizr since I am using only a few HTML5
features and loading a large script isn't worth it just to detect
support for those few things.
To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.
Try window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
You can also use typeof window.localStorage!=="undefined", but the statement above already does it
I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.
If you use jQuery, you can do:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Or, with pure Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Then, you would simply do an IF to test the support:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.
Try catch will do the job :
try{
localStorage.setItem("name",name.value);
localStorage.setItem("post",post.value);
}
catch(e){
alert(e.message);
}
Try:
if(typeof window.localStorage != 'undefined') {
}
if (window.localStorage){
alert('localStorage is supported');
window.localStorage.setItem("whatever", "string value");
}
Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
function script(){
if(ls){
alert('Yes');
} else {
alert('No');
}
}
<button onclick="script()">Local Storage Support?</button>
I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.
Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.
So without further ado here is my code:
/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */
if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);
sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));
if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};
sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'session storage' support. [END] */
/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */
if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);
localStorage.setItem(ls_test_itm_key, String(ls_test_val));
if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};
localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'local storage' support. [END] */
/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */
/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */
if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'web storage' support. [END] */

Categories

Resources