JavaScript中"!!"的含义及代码data未定义报错咨询
!! in Your Code & Fixing the "data is not defined" Error Let's break this down clearly, starting with what !! does, then why you're hitting that error, and how to fix it.
What !! Does in JavaScript
The double negation !! is a common shorthand to convert any value into its boolean equivalent—it works exactly like the Boolean() function, but it's more concise. Here's the breakdown:
- The first
!flips the value to its opposite boolean state (e.g.,!undefinedbecomestrue,!{}becomesfalse). - The second
!flips it back to the actual boolean representation of the original value.
For example:
!!undefined→false!!null→false!!""→false!!{}→true!!"test"→true
In your code, !!data && _.mapObject(...) is trying to use short-circuit evaluation: if data is a "truthy" value (exists and isn't empty/undefined), it runs the _.mapObject transformation; otherwise, it would return false for the ajax data parameter.
Why You're Getting "data is not defined"
The error isn't caused by the !! operator itself—it's about the data variable. When you write !!data, JavaScript tries to look up the data variable in the current scope. If that variable was never declared (or isn't accessible in this scope), it throws a ReferenceError because it can't find the variable at all.
Unlike accessing a non-existent object property (which returns undefined), accessing an undeclared variable will always trigger an error—even when using !! on it.
How to Fix the Error
You need to safely check if data exists before trying to use it. The most reliable way to avoid the error is to use typeof data !== 'undefined' (since typeof doesn't throw errors for undeclared variables). Here's how to adjust your code:
data: typeof data !== 'undefined' && data ? _.mapObject(data, function(value) { return $.toJSON(value); }) : undefined,
This does two key things:
- First checks if
datais even declared (usingtypeofto avoid errors). - If it exists and is truthy, runs the
_.mapObjecttransformation; otherwise, sets the ajaxdataparameter toundefined(jQuery handles this correctly by not sending extra data).
Alternatively, if you expect data to be an object (even an empty one), you could initialize it earlier in your code to avoid the issue entirely:
const data = data || {}; // Initialize with empty object if data is undefined/falsy
Just make sure this line runs before your ajax call, and that data is in scope.
内容的提问来源于stack exchange,提问作者Mohammed ESSABRI

