如何正确判断字符串不等于指定值?以ev.target.id !== "dragPos"为例
ev.target.id不等于"dragPos"的方法 Hey there! Let's work through this properly. First, let's fix the syntax issue in your original code snippet, then cover the actual comparison logic and edge cases you might want to account for.
1. Fix the Syntax Error First
Your original code has mismatched parentheses that will break execution:
if((... && ev.target.id !== "dragPos"){
Notice the extra opening parenthesis ( before the ... and a missing closing parenthesis for the if condition. The corrected basic structure should look like one of these:
// If your preceding condition doesn't need extra parentheses for clarity if (... && ev.target.id !== "dragPos") { // Your logic here } // Or if you want to wrap the preceding condition in parentheses if ((yourPrecedingCondition) && ev.target.id !== "dragPos") { // Your logic here }
2. The Core Comparison: !== is Correct (But Watch Edge Cases)
Using !== "dragPos" is the right approach here—it’s the strict inequality operator, which checks both value and type, avoiding unexpected matches from type coercion (like != would allow). However, there are a couple of edge cases to keep in mind:
Case 1:
ev.targetmight benullorundefined
If there’s a scenario whereev.targetcould be null (e.g., the event is triggered on an element that gets removed from the DOM), accessing.iddirectly will throw an error. Use optional chaining to safely handle this:if (... && ev.target?.id !== "dragPos") { // This skips the id check entirely if ev.target is null/undefined }Case 2: The element has no
idattribute
Ifev.targetexists but has no id,ev.target.idwill be an empty string""."" !== "dragPos"evaluates to true, which is probably what you want—but if you need to explicitly exclude elements without an id, add an extra check:if (... && ev.target.id && ev.target.id !== "dragPos") { // Only runs if the element has an id AND it's not "dragPos" }
3. Quick Confirmation
Just to be clear: !== is exactly the operator you need for this strict inequality check. It ensures you won’t accidentally match values that are coerced to the same type (like a number 0 matching the string "0" with !=). Stick with it for reliable results.
内容的提问来源于stack exchange,提问作者Barcoma

