How can I stop the error message Expected '===' and instead saw '=='.
from appearing in jslint.
Doesn’t seem to be an option.
asked Jun 11, 2011 at 18:55
4
For those using JSHint, you can turn off this warning by setting the option eqeqeq to false in your JSHint options (usually .jshintrc)
"eqeqeq": false
From the documentation: http://jshint.com/docs/options/#eqeqeq
Edit:
If you want to be a good citizen and fix your code to use the recommended comparison instead of turning the warning off, make sure both sides of the comparison are using the same type.
For example:
"123" == 123 // true, I'm lazy and JSHint hates me
"123" === 123 // false, no love
Number("123") === 123 // true, no warning
answered Oct 31, 2015 at 21:49
bubbassaurobubbassauro
3,8192 gold badges47 silver badges44 bronze badges
Although its late its worth, it would help some one who is in need
To disable use —
/* eslint eqeqeq: 0 */
To make it as warning use —
/* eslint eqeqeq: 1 */
answered Oct 10, 2019 at 11:46
2
You are correct that there is no option for that. The only way is to either use ===
or modify the source code. I almost always use ===
anyway. It’s better in general unless you know that ==
is really what you want.
answered Jun 11, 2011 at 19:12
Matthew CrumleyMatthew Crumley
101k24 gold badges107 silver badges129 bronze badges
5
same error show me I can fix by using this way
status.user_profile.toString() === props.props.id.toString()
I’m using react js give example I’m using something like that
id = 1
if I excess params show me like this
params :{ id:"1" }
If I excess this way
id == params.id // output true
If I excess this way
id === params.id // output false
because not 100% eqality so show me error in terminal
Expected '===' and instead saw '=='
So I can think about and fix it by converting same data type like this
id.toString() === params.id.toString() // return true
answered Jul 10, 2020 at 10:23
KashifKashif
1,25815 silver badges19 bronze badges
1
Sure!
node_modules/.bin/eslint assets/js/utils.js
68:30 error Expected '===' and instead saw '==' eqeqeq
✖ 1 problem (1 error, 0 warnings)
node_modules/.bin/eslint --print-config assets/js/utils.js
:
Output
{ "globals": { "Array": false, "ArrayBuffer": false, "Boolean": false, "constructor": false, "DataView": false, "Date": false, "decodeURI": false, "decodeURIComponent": false, "encodeURI": false, "encodeURIComponent": false, "Error": false, "escape": false, "eval": false, "EvalError": false, "Float32Array": false, "Float64Array": false, "Function": false, "hasOwnProperty": false, "Infinity": false, "Int16Array": false, "Int32Array": false, "Int8Array": false, "isFinite": false, "isNaN": false, "isPrototypeOf": false, "JSON": false, "Map": false, "Math": false, "NaN": false, "Number": false, "Object": false, "parseFloat": false, "parseInt": false, "Promise": false, "propertyIsEnumerable": false, "Proxy": false, "RangeError": false, "ReferenceError": false, "Reflect": false, "RegExp": false, "Set": false, "String": false, "Symbol": false, "SyntaxError": false, "System": false, "toLocaleString": false, "toString": false, "TypeError": false, "Uint16Array": false, "Uint32Array": false, "Uint8Array": false, "Uint8ClampedArray": false, "undefined": false, "unescape": false, "URIError": false, "valueOf": false, "WeakMap": false, "WeakSet": false, "__dirname": false, "__filename": false, "arguments": false, "Buffer": false, "clearImmediate": false, "clearInterval": false, "clearTimeout": false, "console": false, "exports": true, "GLOBAL": false, "global": false, "Intl": false, "module": false, "process": false, "require": false, "root": false, "setImmediate": false, "setInterval": false, "setTimeout": false, "addEventListener": false, "alert": false, "AnalyserNode": false, "Animation": false, "AnimationEffectReadOnly": false, "AnimationEffectTiming": false, "AnimationEffectTimingReadOnly": false, "AnimationEvent": false, "AnimationPlaybackEvent": false, "AnimationTimeline": false, "applicationCache": false, "ApplicationCache": false, "ApplicationCacheErrorEvent": false, "atob": false, "Attr": false, "Audio": false, "AudioBuffer": false, "AudioBufferSourceNode": false, "AudioContext": false, "AudioDestinationNode": false, "AudioListener": false, "AudioNode": false, "AudioParam": false, "AudioProcessingEvent": false, "AutocompleteErrorEvent": false, "BarProp": false, "BatteryManager": false, "BeforeUnloadEvent": false, "BiquadFilterNode": false, "Blob": false, "blur": false, "btoa": false, "Cache": false, "caches": false, "CacheStorage": false, "cancelAnimationFrame": false, "cancelIdleCallback": false, "CanvasGradient": false, "CanvasPattern": false, "CanvasRenderingContext2D": false, "CDATASection": false, "ChannelMergerNode": false, "ChannelSplitterNode": false, "CharacterData": false, "clientInformation": false, "ClientRect": false, "ClientRectList": false, "ClipboardEvent": false, "close": false, "closed": false, "CloseEvent": false, "Comment": false, "CompositionEvent": false, "confirm": false, "ConvolverNode": false, "createImageBitmap": false, "Credential": false, "CredentialsContainer": false, "crypto": false, "Crypto": false, "CryptoKey": false, "CSS": false, "CSSAnimation": false, "CSSFontFaceRule": false, "CSSImportRule": false, "CSSKeyframeRule": false, "CSSKeyframesRule": false, "CSSMediaRule": false, "CSSPageRule": false, "CSSRule": false, "CSSRuleList": false, "CSSStyleDeclaration": false, "CSSStyleRule": false, "CSSStyleSheet": false, "CSSSupportsRule": false, "CSSTransition": false, "CSSUnknownRule": false, "CSSViewportRule": false, "customElements": false, "CustomEvent": false, "DataTransfer": false, "DataTransferItem": false, "DataTransferItemList": false, "Debug": false, "defaultStatus": false, "defaultstatus": false, "DelayNode": false, "DeviceMotionEvent": false, "DeviceOrientationEvent": false, "devicePixelRatio": false, "dispatchEvent": false, "document": false, "Document": false, "DocumentFragment": false, "DocumentTimeline": false, "DocumentType": false, "DOMError": false, "DOMException": false, "DOMImplementation": false, "DOMParser": false, "DOMSettableTokenList": false, "DOMStringList": false, "DOMStringMap": false, "DOMTokenList": false, "DragEvent": false, "DynamicsCompressorNode": false, "Element": false, "ElementTimeControl": false, "ErrorEvent": false, "event": false, "Event": false, "EventSource": false, "EventTarget": false, "external": false, "FederatedCredential": false, "fetch": false, "File": false, "FileError": false, "FileList": false, "FileReader": false, "find": false, "focus": false, "FocusEvent": false, "FontFace": false, "FormData": false, "frameElement": false, "frames": false, "GainNode": false, "Gamepad": false, "GamepadButton": false, "GamepadEvent": false, "getComputedStyle": false, "getSelection": false, "HashChangeEvent": false, "Headers": false, "history": false, "History": false, "HTMLAllCollection": false, "HTMLAnchorElement": false, "HTMLAppletElement": false, "HTMLAreaElement": false, "HTMLAudioElement": false, "HTMLBaseElement": false, "HTMLBlockquoteElement": false, "HTMLBodyElement": false, "HTMLBRElement": false, "HTMLButtonElement": false, "HTMLCanvasElement": false, "HTMLCollection": false, "HTMLContentElement": false, "HTMLDataListElement": false, "HTMLDetailsElement": false, "HTMLDialogElement": false, "HTMLDirectoryElement": false, "HTMLDivElement": false, "HTMLDListElement": false, "HTMLDocument": false, "HTMLElement": false, "HTMLEmbedElement": false, "HTMLFieldSetElement": false, "HTMLFontElement": false, "HTMLFormControlsCollection": false, "HTMLFormElement": false, "HTMLFrameElement": false, "HTMLFrameSetElement": false, "HTMLHeadElement": false, "HTMLHeadingElement": false, "HTMLHRElement": false, "HTMLHtmlElement": false, "HTMLIFrameElement": false, "HTMLImageElement": false, "HTMLInputElement": false, "HTMLIsIndexElement": false, "HTMLKeygenElement": false, "HTMLLabelElement": false, "HTMLLayerElement": false, "HTMLLegendElement": false, "HTMLLIElement": false, "HTMLLinkElement": false, "HTMLMapElement": false, "HTMLMarqueeElement": false, "HTMLMediaElement": false, "HTMLMenuElement": false, "HTMLMetaElement": false, "HTMLMeterElement": false, "HTMLModElement": false, "HTMLObjectElement": false, "HTMLOListElement": false, "HTMLOptGroupElement": false, "HTMLOptionElement": false, "HTMLOptionsCollection": false, "HTMLOutputElement": false, "HTMLParagraphElement": false, "HTMLParamElement": false, "HTMLPictureElement": false, "HTMLPreElement": false, "HTMLProgressElement": false, "HTMLQuoteElement": false, "HTMLScriptElement": false, "HTMLSelectElement": false, "HTMLShadowElement": false, "HTMLSourceElement": false, "HTMLSpanElement": false, "HTMLStyleElement": false, "HTMLTableCaptionElement": false, "HTMLTableCellElement": false, "HTMLTableColElement": false, "HTMLTableElement": false, "HTMLTableRowElement": false, "HTMLTableSectionElement": false, "HTMLTemplateElement": false, "HTMLTextAreaElement": false, "HTMLTitleElement": false, "HTMLTrackElement": false, "HTMLUListElement": false, "HTMLUnknownElement": false, "HTMLVideoElement": false, "IDBCursor": false, "IDBCursorWithValue": false, "IDBDatabase": false, "IDBEnvironment": false, "IDBFactory": false, "IDBIndex": false, "IDBKeyRange": false, "IDBObjectStore": false, "IDBOpenDBRequest": false, "IDBRequest": false, "IDBTransaction": false, "IDBVersionChangeEvent": false, "Image": false, "ImageBitmap": false, "ImageData": false, "indexedDB": false, "innerHeight": false, "innerWidth": false, "InputEvent": false, "InputMethodContext": false, "IntersectionObserver": false, "IntersectionObserverEntry": false, "KeyboardEvent": false, "KeyframeEffect": false, "KeyframeEffectReadOnly": false, "length": false, "localStorage": false, "location": false, "Location": false, "locationbar": false, "matchMedia": false, "MediaElementAudioSourceNode": false, "MediaEncryptedEvent": false, "MediaError": false, "MediaKeyError": false, "MediaKeyEvent": false, "MediaKeyMessageEvent": false, "MediaKeys": false, "MediaKeySession": false, "MediaKeyStatusMap": false, "MediaKeySystemAccess": false, "MediaList": false, "MediaQueryList": false, "MediaQueryListEvent": false, "MediaSource": false, "MediaRecorder": false, "MediaStream": false, "MediaStreamAudioDestinationNode": false, "MediaStreamAudioSourceNode": false, "MediaStreamEvent": false, "MediaStreamTrack": false, "menubar": false, "MessageChannel": false, "MessageEvent": false, "MessagePort": false, "MIDIAccess": false, "MIDIConnectionEvent": false, "MIDIInput": false, "MIDIInputMap": false, "MIDIMessageEvent": false, "MIDIOutput": false, "MIDIOutputMap": false, "MIDIPort": false, "MimeType": false, "MimeTypeArray": false, "MouseEvent": false, "moveBy": false, "moveTo": false, "MutationEvent": false, "MutationObserver": false, "MutationRecord": false, "name": false, "NamedNodeMap": false, "navigator": false, "Navigator": false, "Node": false, "NodeFilter": false, "NodeIterator": false, "NodeList": false, "Notification": false, "OfflineAudioCompletionEvent": false, "OfflineAudioContext": false, "offscreenBuffering": false, "onbeforeunload": true, "onblur": true, "onerror": true, "onfocus": true, "onload": true, "onresize": true, "onunload": true, "open": false, "openDatabase": false, "opener": false, "opera": false, "Option": false, "OscillatorNode": false, "outerHeight": false, "outerWidth": false, "PageTransitionEvent": false, "pageXOffset": false, "pageYOffset": false, "parent": false, "PasswordCredential": false, "Path2D": false, "performance": false, "Performance": false, "PerformanceEntry": false, "PerformanceMark": false, "PerformanceMeasure": false, "PerformanceNavigation": false, "PerformanceResourceTiming": false, "PerformanceTiming": false, "PeriodicWave": false, "Permissions": false, "PermissionStatus": false, "personalbar": false, "Plugin": false, "PluginArray": false, "PopStateEvent": false, "postMessage": false, "print": false, "ProcessingInstruction": false, "ProgressEvent": false, "PromiseRejectionEvent": false, "prompt": false, "PushManager": false, "PushSubscription": false, "RadioNodeList": false, "Range": false, "ReadableByteStream": false, "ReadableStream": false, "removeEventListener": false, "Request": false, "requestAnimationFrame": false, "requestIdleCallback": false, "resizeBy": false, "resizeTo": false, "Response": false, "RTCIceCandidate": false, "RTCSessionDescription": false, "RTCPeerConnection": false, "screen": false, "Screen": false, "screenLeft": false, "ScreenOrientation": false, "screenTop": false, "screenX": false, "screenY": false, "ScriptProcessorNode": false, "scroll": false, "scrollbars": false, "scrollBy": false, "scrollTo": false, "scrollX": false, "scrollY": false, "SecurityPolicyViolationEvent": false, "Selection": false, "self": false, "ServiceWorker": false, "ServiceWorkerContainer": false, "ServiceWorkerRegistration": false, "sessionStorage": false, "ShadowRoot": false, "SharedKeyframeList": false, "SharedWorker": false, "showModalDialog": false, "SiteBoundCredential": false, "speechSynthesis": false, "SpeechSynthesisEvent": false, "SpeechSynthesisUtterance": false, "status": false, "statusbar": false, "stop": false, "Storage": false, "StorageEvent": false, "styleMedia": false, "StyleSheet": false, "StyleSheetList": false, "SubtleCrypto": false, "SVGAElement": false, "SVGAltGlyphDefElement": false, "SVGAltGlyphElement": false, "SVGAltGlyphItemElement": false, "SVGAngle": false, "SVGAnimateColorElement": false, "SVGAnimatedAngle": false, "SVGAnimatedBoolean": false, "SVGAnimatedEnumeration": false, "SVGAnimatedInteger": false, "SVGAnimatedLength": false, "SVGAnimatedLengthList": false, "SVGAnimatedNumber": false, "SVGAnimatedNumberList": false, "SVGAnimatedPathData": false, "SVGAnimatedPoints": false, "SVGAnimatedPreserveAspectRatio": false, "SVGAnimatedRect": false, "SVGAnimatedString": false, "SVGAnimatedTransformList": false, "SVGAnimateElement": false, "SVGAnimateMotionElement": false, "SVGAnimateTransformElement": false, "SVGAnimationElement": false, "SVGCircleElement": false, "SVGClipPathElement": false, "SVGColor": false, "SVGColorProfileElement": false, "SVGColorProfileRule": false, "SVGComponentTransferFunctionElement": false, "SVGCSSRule": false, "SVGCursorElement": false, "SVGDefsElement": false, "SVGDescElement": false, "SVGDiscardElement": false, "SVGDocument": false, "SVGElement": false, "SVGElementInstance": false, "SVGElementInstanceList": false, "SVGEllipseElement": false, "SVGEvent": false, "SVGExternalResourcesRequired": false, "SVGFEBlendElement": false, "SVGFEColorMatrixElement": false, "SVGFEComponentTransferElement": false, "SVGFECompositeElement": false, "SVGFEConvolveMatrixElement": false, "SVGFEDiffuseLightingElement": false, "SVGFEDisplacementMapElement": false, "SVGFEDistantLightElement": false, "SVGFEDropShadowElement": false, "SVGFEFloodElement": false, "SVGFEFuncAElement": false, "SVGFEFuncBElement": false, "SVGFEFuncGElement": false, "SVGFEFuncRElement": false, "SVGFEGaussianBlurElement": false, "SVGFEImageElement": false, "SVGFEMergeElement": false, "SVGFEMergeNodeElement": false, "SVGFEMorphologyElement": false, "SVGFEOffsetElement": false, "SVGFEPointLightElement": false, "SVGFESpecularLightingElement": false, "SVGFESpotLightElement": false, "SVGFETileElement": false, "SVGFETurbulenceElement": false, "SVGFilterElement": false, "SVGFilterPrimitiveStandardAttributes": false, "SVGFitToViewBox": false, "SVGFontElement": false, "SVGFontFaceElement": false, "SVGFontFaceFormatElement": false, "SVGFontFaceNameElement": false, "SVGFontFaceSrcElement": false, "SVGFontFaceUriElement": false, "SVGForeignObjectElement": false, "SVGGElement": false, "SVGGeometryElement": false, "SVGGlyphElement": false, "SVGGlyphRefElement": false, "SVGGradientElement": false, "SVGGraphicsElement": false, "SVGHKernElement": false, "SVGICCColor": false, "SVGImageElement": false, "SVGLangSpace": false, "SVGLength": false, "SVGLengthList": false, "SVGLinearGradientElement": false, "SVGLineElement": false, "SVGLocatable": false, "SVGMarkerElement": false, "SVGMaskElement": false, "SVGMatrix": false, "SVGMetadataElement": false, "SVGMissingGlyphElement": false, "SVGMPathElement": false, "SVGNumber": false, "SVGNumberList": false, "SVGPaint": false, "SVGPathElement": false, "SVGPathSeg": false, "SVGPathSegArcAbs": false, "SVGPathSegArcRel": false, "SVGPathSegClosePath": false, "SVGPathSegCurvetoCubicAbs": false, "SVGPathSegCurvetoCubicRel": false, "SVGPathSegCurvetoCubicSmoothAbs": false, "SVGPathSegCurvetoCubicSmoothRel": false, "SVGPathSegCurvetoQuadraticAbs": false, "SVGPathSegCurvetoQuadraticRel": false, "SVGPathSegCurvetoQuadraticSmoothAbs": false, "SVGPathSegCurvetoQuadraticSmoothRel": false, "SVGPathSegLinetoAbs": false, "SVGPathSegLinetoHorizontalAbs": false, "SVGPathSegLinetoHorizontalRel": false, "SVGPathSegLinetoRel": false, "SVGPathSegLinetoVerticalAbs": false, "SVGPathSegLinetoVerticalRel": false, "SVGPathSegList": false, "SVGPathSegMovetoAbs": false, "SVGPathSegMovetoRel": false, "SVGPatternElement": false, "SVGPoint": false, "SVGPointList": false, "SVGPolygonElement": false, "SVGPolylineElement": false, "SVGPreserveAspectRatio": false, "SVGRadialGradientElement": false, "SVGRect": false, "SVGRectElement": false, "SVGRenderingIntent": false, "SVGScriptElement": false, "SVGSetElement": false, "SVGStopElement": false, "SVGStringList": false, "SVGStylable": false, "SVGStyleElement": false, "SVGSVGElement": false, "SVGSwitchElement": false, "SVGSymbolElement": false, "SVGTests": false, "SVGTextContentElement": false, "SVGTextElement": false, "SVGTextPathElement": false, "SVGTextPositioningElement": false, "SVGTitleElement": false, "SVGTransform": false, "SVGTransformable": false, "SVGTransformList": false, "SVGTRefElement": false, "SVGTSpanElement": false, "SVGUnitTypes": false, "SVGURIReference": false, "SVGUseElement": false, "SVGViewElement": false, "SVGViewSpec": false, "SVGVKernElement": false, "SVGZoomAndPan": false, "SVGZoomEvent": false, "Text": false, "TextDecoder": false, "TextEncoder": false, "TextEvent": false, "TextMetrics": false, "TextTrack": false, "TextTrackCue": false, "TextTrackCueList": false, "TextTrackList": false, "TimeEvent": false, "TimeRanges": false, "toolbar": false, "top": false, "Touch": false, "TouchEvent": false, "TouchList": false, "TrackEvent": false, "TransitionEvent": false, "TreeWalker": false, "UIEvent": false, "URL": false, "URLSearchParams": false, "ValidityState": false, "VTTCue": false, "WaveShaperNode": false, "WebGLActiveInfo": false, "WebGLBuffer": false, "WebGLContextEvent": false, "WebGLFramebuffer": false, "WebGLProgram": false, "WebGLRenderbuffer": false, "WebGLRenderingContext": false, "WebGLShader": false, "WebGLShaderPrecisionFormat": false, "WebGLTexture": false, "WebGLUniformLocation": false, "WebSocket": false, "WheelEvent": false, "window": false, "Window": false, "Worker": false, "XDomainRequest": false, "XMLDocument": false, "XMLHttpRequest": false, "XMLHttpRequestEventTarget": false, "XMLHttpRequestProgressEvent": false, "XMLHttpRequestUpload": false, "XMLSerializer": false, "XPathEvaluator": false, "XPathException": false, "XPathExpression": false, "XPathNamespace": false, "XPathNSResolver": false, "XPathResult": false, "XSLTProcessor": false }, "env": { "es6": true, "node": true, "browser": true }, "rules": { "accessor-pairs": "error", "arrow-spacing": [ "error", { "before": true, "after": true } ], "block-spacing": [ "error", "always" ], "brace-style": [ "error", "1tbs", { "allowSingleLine": true } ], "camelcase": [ "error", { "properties": "never" } ], "comma-dangle": [ "error", { "arrays": "never", "objects": "never", "imports": "never", "exports": "never", "functions": "never" } ], "comma-spacing": [ "error", { "before": false, "after": true } ], "comma-style": [ "error", "last" ], "constructor-super": "error", "curly": [ "error", "multi-line" ], "dot-location": [ "error", "property" ], "eol-last": "error", "eqeqeq": [ "error", "smart" ], "func-call-spacing": [ "error", "never" ], "generator-star-spacing": [ "error", { "before": true, "after": true } ], "handle-callback-err": [ "error", "^(err|error)$" ], "indent": [ "error", 2, { "SwitchCase": 1 } ], "key-spacing": [ "error", { "beforeColon": false, "afterColon": true } ], "keyword-spacing": [ "error", { "before": true, "after": true } ], "new-cap": [ "error", { "newIsCap": true, "capIsNew": false } ], "new-parens": "error", "no-array-constructor": "error", "no-caller": "error", "no-class-assign": "error", "no-compare-neg-zero": "error", "no-cond-assign": "error", "no-const-assign": "error", "no-constant-condition": [ "error", { "checkLoops": false } ], "no-control-regex": "error", "no-debugger": 0, "no-delete-var": "error", "no-dupe-args": "error", "no-dupe-class-members": "error", "no-dupe-keys": "error", "no-duplicate-case": "error", "no-empty-character-class": "error", "no-empty-pattern": "error", "no-eval": "error", "no-ex-assign": "error", "no-extend-native": "error", "no-extra-bind": "error", "no-extra-boolean-cast": "error", "no-extra-parens": [ "error", "functions" ], "no-fallthrough": "error", "no-floating-decimal": "error", "no-func-assign": "error", "no-global-assign": "error", "no-implied-eval": "error", "no-inner-declarations": [ "error", "functions" ], "no-invalid-regexp": "error", "no-irregular-whitespace": "error", "no-iterator": "error", "no-label-var": "error", "no-labels": [ "error", { "allowLoop": false, "allowSwitch": false } ], "no-lone-blocks": "error", "no-mixed-operators": [ 1, { "groups": [ [ "==", "!=", "===", "!==", ">", ">=", "<", "<=" ], [ "&&", "||" ], [ "in", "instanceof" ] ], "allowSamePrecedence": true } ], "no-mixed-spaces-and-tabs": "error", "no-multi-spaces": "error", "no-multi-str": "error", "no-multiple-empty-lines": [ "error", { "max": 1, "maxEOF": 0 } ], "no-negated-in-lhs": "error", "no-new": "error", "no-new-func": "error", "no-new-object": "error", "no-new-require": "error", "no-new-symbol": "error", "no-new-wrappers": "error", "no-obj-calls": "error", "no-octal": "error", "no-octal-escape": "error", "no-path-concat": "error", "no-proto": "error", "no-redeclare": "error", "no-regex-spaces": "error", "no-return-assign": [ "error", "except-parens" ], "no-return-await": "error", "no-self-assign": "error", "no-self-compare": "error", "no-sequences": "error", "no-shadow-restricted-names": "error", "no-sparse-arrays": "error", "no-tabs": "error", "no-template-curly-in-string": "error", "no-this-before-super": "error", "no-throw-literal": "error", "no-trailing-spaces": "error", "no-undef": "error", "no-undef-init": "error", "no-unexpected-multiline": "error", "no-unmodified-loop-condition": "error", "no-unneeded-ternary": [ "error", { "defaultAssignment": false } ], "no-unreachable": "error", "no-unsafe-finally": "error", "no-unsafe-negation": "error", "no-unused-expressions": [ "error", { "allowShortCircuit": true, "allowTernary": true, "allowTaggedTemplates": true } ], "no-unused-vars": [ "error", { "vars": "all", "args": "none", "ignoreRestSiblings": true } ], "no-use-before-define": [ "error", { "functions": false, "classes": false, "variables": false } ], "no-useless-call": "error", "no-useless-computed-key": "error", "no-useless-constructor": "error", "no-useless-escape": "error", "no-useless-rename": "error", "no-useless-return": "error", "no-whitespace-before-property": "error", "no-with": "error", "object-property-newline": [ "error", { "allowMultiplePropertiesPerLine": true } ], "one-var": [ "error", { "initialized": "never" } ], "operator-linebreak": [ "error", "after", { "overrides": { "?": "before", ":": "before" } } ], "padded-blocks": [ "error", { "blocks": "never", "switches": "never", "classes": "never" } ], "prefer-promise-reject-errors": "error", "quotes": [ "error", "single", { "avoidEscape": true, "allowTemplateLiterals": true } ], "rest-spread-spacing": [ "error", "never" ], "semi": [ "error", "never" ], "semi-spacing": [ "error", { "before": false, "after": true } ], "space-before-blocks": [ "error", "always" ], "space-before-function-paren": [ "error", "always" ], "space-in-parens": [ "error", "never" ], "space-infix-ops": "error", "space-unary-ops": [ "error", { "words": true, "nonwords": false } ], "spaced-comment": [ "error", "always", { "line": { "markers": [ "*package", "!", "/", "," ] }, "block": { "balanced": true, "markers": [ "*package", "!", ",", ":", "::", "flow-include" ], "exceptions": [ "*" ] } } ], "symbol-description": "error", "template-curly-spacing": [ "error", "never" ], "template-tag-spacing": [ "error", "never" ], "unicode-bom": [ "error", "never" ], "use-isnan": "error", "valid-typeof": [ "error", { "requireStringLiterals": true } ], "wrap-iife": [ "error", "any", { "functionPrototypeMethods": true } ], "yield-star-spacing": [ "error", "both" ], "yoda": [ "error", "never" ], "import/export": "error", "import/first": "error", "import/no-duplicates": "error", "import/no-webpack-loader-syntax": "error", "node/no-deprecated-api": "error", "node/process-exit-as-throw": "error", "promise/param-names": "error", "standard/array-bracket-even-spacing": [ "error", "either" ], "standard/computed-property-even-spacing": [ "error", "even" ], "standard/no-callback-literal": "error", "standard/object-curly-even-spacing": [ "error", "either" ] }, "parserOptions": { "ecmaVersion": 8, "ecmaFeatures": { "globalReturn": true, "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "import", "node", "promise", "standard", "html" ], "root": true, "parser": "/home/dotnet/projects/napp/webviewer2/node_modules/babel-eslint/index.js", "extends": "standard" }
Я только что обновил Visual Studio 2017 от RC до финала. Я не получил следующую ошибку, но недавно я получил эту ошибку. При создании проекта я получаю следующую ошибку, которая мешает запуску веб-проекта:
Severity Code Description Project File Line Suppression State
Error eqeqeq (ESLint) Expected '===' and instead saw '=='. VistaBest.Shop.Web C:***Request.js 21
Как отключить ошибку сборки JavaScript в Visual Studio 2017?
10 март 2017, в 19:34
Поделиться
Источник
7 ответов
Я думаю, найти решение:
- Откройте
Tools > Options
- Перейдите к
Text Editor > JavaScript/TypeScript > EsLint
(в VS2017 15.8 этоLinting
неEsLint
) - Установите
Enable ESLint
вFalse
Visual Studio> = 15.8.5
Mohammad Dayyan
10 март 2017, в 21:23
Поделиться
В Visual Studio 2017 (v 15.8.0):
Вариант 1: Параметры> Ошибки JS
- Откройте
Tools > Options
- Перейдите к
Text Editor > JavaScript/TypeScript > Code Validation
- Установите для параметра
Enable JavaScript errors
значениеfalse
- или установите для параметра
Enable JavaScript errors
значениеtrue
иShow errors as warnings
значениеtrue
Мне нужно было перезапустить Visual Studio, чтобы это вступило в силу.
Вариант 2: Параметры> Линтинг
Ниже есть еще один вариант, который позволит вам отредактировать глобальные настройки линтинга:
Вариант 3: файл .eslint
Вы также можете создать файл с именем .eslintrc
в корневом каталоге вашего проекта.
Вариант 4: команды ESLint в файле
Смотрите @user9153924 ответ
Ресурсы
- Синтаксис файла ESLint
- Правила ESLint
Brad
17 авг. 2018, в 20:48
Поделиться
Я попробовал решение Мохаммада, но это не сработало. Мне удалось выполнить следующие действия:
- Righ нажмите на свой веб файл .csproj.
- В первом
<PropertyGroup>
добавить следующую запись:
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
Rafael dos Santos
07 апр. 2017, в 20:41
Поделиться
Добавьте /*eslint eqeqeq: ["error", "smart"]*/
в первую строку вашего кода Javascript, чтобы удалить ошибки. https://eslint.org/docs/rules/eqeqeq
Следующее решение Мухаммеда отключит ESLint для проверки синтаксиса. Это работает в VS2015 и должно работать в более поздних версиях.
user9153924
29 дек. 2017, в 18:09
Поделиться
Мне просто нужно было изменить поведение правила «eqeqeq», чтобы включить «умный»:
Отредактируйте файл .eslintrc, найденный в корневой папке пользователя, упомянутой в других ответах.
Внесение изменений в раздел правил путем добавления умного правила
"rules": {
"eqeqeq": [2, "smart"],
Скопировано из веб-статьи: эта опция заставляет использовать === и! == за исключением следующих случаев:
- Сравнение двух литеральных значений
- Оценка стоимости typeof
- Сравнение с нулем
Я нашел подробности по адресу: https://eslint.org/docs/2.0.0/rules/eqeqeq
cjl
31 окт. 2018, в 08:32
Поделиться
Я попробовал решение Mohammad, но не повезло, я последовал за ответом Rafeel и вместо того, чтобы добавить свой предложенный образец кода, я удалил код ниже web .csproj
и, наконец, смог создать и запустить свой проект. Было два места, где вы должны удалить это в том же файле. Тем не менее, я не знаю, как удаленный код повлияет на мое решение.
<Import Project="$(MSBuildExtensionsPath32)MicrosoftVisualStudiov$(VisualStudioVersion)TypeScriptMicrosoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)MicrosoftVisualStudiov$(VisualStudioVersion)TypeScriptMicrosoft.TypeScript.Default.props')" />
Надеюсь, это также поможет кому-то сохранить этот день..!!!
SilentCoder
13 дек. 2017, в 13:27
Поделиться
В VS 2017 Enterprise это должно быть так:
Scarlett Le
28 нояб. 2017, в 04:50
Поделиться
Ещё вопросы
- 1как получить и установить параметры в Camel HTTP Proxy
- 0Модификация заголовков PHP
- 1Проблема с многопоточностью при подключении к нескольким устройствам одновременно
- 0Рассчитать сумму каждой строки с помощью jQuery при изменении значения в текстовом поле
- 0AngularJS: формат ввода даты
- 0Оптимизировать функцию ucallwords
- 0Показать изображение с помощью onMouseOver, причем изображение находится за пределами li-тега
- 0Перейдите в раздел <section>, нажав <a> на той же странице
- 0Автоматическая прокрутка аккордеона в верхнюю часть выделенного раздела
- 0Как установить значение высоты div динамически?
- 0MySQL вставка не вставляя предполагаемое значение
- 1Ошибка при создании bean-компонента с именем securityConfig: не удалось внедрить автоназначенные зависимости
- 1Где мой AlertDialog?
- 0загрузить функцию после загрузки другой
- 0Структура данных из MySql в FireBase (NOSQL db)
- 0JQuery прервать AJAX вызывает ошибку 0
- 0Избавьтесь от случая переключателя, используя массив функторов
- 1Стандартное отклонение числа между n строками и n столбцами 3 массивов
- 0вызов службы асинхронного отдыха с помощью jquery
- 1java.lang.NumberFormatException для входной строки «»
- 0Как убрать пустое место с сайта?
- 0Angular Controller передает данные другому контроллеру при изменении страницы
- 1Загрузить файл на сервер Apache
- 0Неустранимая ошибка PHP: класс «FacebookAds Object AdAccount» не найден в
- 0Перенаправить из .net aspx в html
- 0Нижний колонтитул PHP / CSS Не останется внизу страницы, если на странице нет текста [дубликата]
- 0pushstate работает только один раз
- 0Служба недоступна при использовании 2 вызовов CURL на разные URL — PHP
- 1Битовая упаковка номеров фраз LZW
- 1Обновите панель сведений с помощью нового окна управления пользователями MVVM WPF
- 1Класс C # Деинициализация динамической памяти
- 0wxStreamToTextRedirector новые строки потеряны
- 0Вставка и удаление функций бинарного дерева поиска
- 1Как определить, что MMS полностью загружено в Android?
- 0Не могу использовать h: commandLink внутри <li>, чтобы сделать лениво загруженные вкладки jquery
- 1Как отменить выбор области «Использовать» в таблице электронных таблиц после использования функции выбора
- 1«Отсутствует издатель google_id_token» при создании документа OpenApi для конечных точек облака с Auth0
- 0Сделать изменение формы (например, черновик / отделка) на Symfony2
- 0C ++ 11 — bad_alloc на constexpr
- 0Visual Studio думает, что функции уже определены?
- 0Постоянно сохраняйте отзывчивое / изменяемое содержимое сетки в пределах размера области просмотра
- 0Как отформатировать сообщение электронной почты, которое говорит пользователям Outlook «просматривать в HTML» при просмотре в текстовом режиме?
- 1Можем ли мы использовать функцию переопределения фильтра на сторонних контроллерах?
- 0Необработанное исключение DirectX11.1 Рендеринг 2D-графики
- 0Создание списка внутри контейнера в PHP
- 1Как включить представление, созданное в XML-файле на моем основном макете
- 0Логический параметр в функции создает ошибку?
- 0AngularJS Пропускная способность между контроллерами Производительность
- 1Изменить стандартное поведение onListItemClick для ListView
- 0Отладка VS 2008 — Найти, какой диалог загружен
На чтение 5 мин. Просмотров 46 Опубликовано 15.12.2019
Как я могу остановить сообщение об ошибке Expected ‘===’ and instead saw ‘==’. от появления в jslint. Кажется, это не вариант.
Для тех, кто использует JSHint, вы можете отключить это предупреждение, установив для параметра JSHint значение eqeqeq значение false (обычно .jshintrc)
Если вы хотите быть хорошим гражданином и исправить свой код, чтобы использовать рекомендуемое сравнение вместо выключения предупреждения, убедитесь, что обе стороны сравнения используют один и тот же тип.
Это довольно жарко от прессы.
Дуглас Крокфорд только что добавил параметр «eqeq» к инструменту JSLint.
См. один из редакций от 12 июня 2011 года в GitHub:
Ad время написания не было обновлено на первой странице JSLint, но я протестировал его со следующим и не получил предупреждений == :
Recently I was running some of my code through JSLint when I came up with this error. The thing I think is funny about this error though is that it automatically assumes that all == should be ===.
Does that really make any sense? I could see a lot of instances that you would not want to compare type, and I am worried that this could actually cause problems.
The word «Expected» would imply that this should be done EVERY time. That is what does not make sense to me.
8 Answers 8
IMO, blindly using === , without trying to understand how type conversion works doesn’t make much sense.
The primary fear about the Equals operator == is that the comparison rules depending on the types compared can make the operator non-transitive, for example, if:
Doesn’t really guarantees that:
The Strict Equals operator === is not really necessary when you compare values of the same type, the most common example:
We compare the result of the typeof operator, which is always a string, with a string literal.
Or when you know the type coercion rules, for example, check if something is null or undefined something:
JSLint is inherently more defensive than the Javascript syntax allows for.
From the JSLint documentation:
The == and != operators do type coercion before comparing. This is bad because it causes ‘
‘ == 0 to be true. This can mask type errors.
When comparing to any of the following values, use the === or !== operators (which do not do type coercion): 0 » undefined null false true
If you only care that a value is truthy or falsy, then use the short form. Instead of
The === and !== operators are preferred.
Keep in mind that JSLint enforces one persons idea of what good JavaScript should be. You still have to use common sense when implementing the changes it suggests.
In general, comparing type and value will make your code safer (you will not run into the unexpected behavior when type conversion doesn’t do what you think it should).
Triple-equal is different to double-equal because in addition to checking whether the two sides are the same value, triple-equal also checks that they are the same data type.
So («4» == 4) is true, whereas («4» === 4) is false.
Triple-equal also runs slightly quicker, because JavaScript doesn’t have to waste time doing any type conversions prior to giving you the answer.
JSLint is deliberately aimed at making your JavaScript code as strict as possible, with the aim of reducing obscure bugs. It highlights this sort of thing to try to get you to code in a way that forces you to respect data types.
But the good thing about JSLint is that it is just a guide. As they say on the site, it will hurt your feelings, even if you’re a very good JavaScript programmer. But you shouldn’t feel obliged to follow its advice. If you’ve read what it has to say and you understand it, but you are sure your code isn’t going to break, then there’s no compulsion on you to change anything.
You can even tell JSLint to ignore categories of checks if you don’t want to be bombarded with warnings that you’re not going to do anything about.
Learning, cleaning up and updating a snippet I found on-line. I’ve been adding the somewhat new code «use strict»; and the way the snippet has been programmed is alike the below snippet;
Line 83 is pulling up the following error;
I know how to bracket this section however I’m not sure how the return is doing exactly, whether I should ass the < before the return and then close up after dragging = null; ?
This is also used as seen below;
1 Answer 1
Some automated tools consider placing a «naked» statement after a conditional (i.e. a statement not wrapped in a block) as bad practice.
Some even warn about multiple return statements or about writing if (x == 3) . instead of if (3 == x) . .
The original statement if (!dragging) return; is perfectly valid Javascript. If it’s more readable for you then just keep it that way and shut up that warning (there should be options to do that).