如何判断数组是否包含0并删除?现有JS代码失效求助
Hey there! Let's figure out why your current code isn't working, then walk through solid solutions to remove the 0 from your array.
What's Wrong With Your Current Code?
Let's break down the issues step by step:
IDs.filter(Number)doesn't modify the original array: Thefilter()method returns a new array with the filtered elements—you have to assign this new array back toIDsfor changes to take effect.IDs.splice(0)is doing the wrong thing: This command removes all elements starting from index 0 (it empties the entire array!), not just the value0.andisn't valid JS syntax: JavaScript uses&&for logical "and", but you don't even need this here anyway.
Solution 1: Use filter() (Simplest & Most Reliable)
If you want to remove all instances of 0 from the array (not just the first one), filter() is your best bet. It's clean and handles edge cases automatically:
const IDs = [671322109, 671322111, 0, 671322113]; // Option 1: Explicitly remove only the value 0 IDs = IDs.filter(id => id !== 0); // Option 2: Use Number to filter out all falsy values (0, null, undefined, etc.) // Only use this if you're sure you want to remove all falsy values, not just 0 // IDs = IDs.filter(Number); console.log(IDs); // Output: [671322109, 671322111, 671322113]
You don't even need to check if 0 exists first—filter() will just return the original array if there's no 0 to remove.
Solution 2: Use indexOf() + splice() (If You Need to Check First)
If you specifically want to run some extra logic only if 0 exists before removing it, use indexOf() to find its position, then splice() to delete it:
const IDs = [671322109, 671322111, 0, 671322113]; const zeroPosition = IDs.indexOf(0); if (zeroPosition !== -1) { // Remove 1 element starting at the index where 0 was found IDs.splice(zeroPosition, 1); // Add any extra logic here that should run only when 0 is removed } console.log(IDs); // Output: [671322109, 671322111, 671322113]
Note: This only removes the first occurrence of 0. If your array might have multiple 0s, stick with the filter() method.
内容的提问来源于stack exchange,提问作者Ahmed Halim

