You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中indexOf查找数组元素返回-1而非预期值的问题求助

Understanding Why Your Array Lookup Isn't Working

Hey there! Let's break down why your indexOf call is returning -1 instead of 0, and why that === comparison is evaluating to false.

The Root Cause: Reference Types vs. Primitive Types

In JavaScript, arrays are reference types, unlike primitive values (like strings, numbers, or booleans). Here's the critical difference:

  • For primitive types, === checks if the values are identical.
  • For reference types (arrays, objects, etc.), === checks if the two variables point to the exact same object in memory—not just if their contents match.

In your code:

  • points[0] refers to one array object stored in your browser's memory.
  • The ["2.408","38.8"] you pass to indexOf is a brand new array object, created on the spot when you run that line.

Even though their contents are identical, they're two separate objects with different memory addresses. That's why points[0] === ["2.408","38.8"] returns false, and indexOf (which uses strict equality under the hood) can't find a match.

How to Fix It

To find the index of your nested array, you need to compare the contents of the arrays instead of their references. Here are two straightforward approaches:

1. Use findIndex with explicit value checks

This is the most reliable method, especially if your nested arrays have a fixed structure:

var points = [ ["2.408","38.8"], ["2.410","38.8"], ["2.410","38.76"] ];
var position = points.findIndex(item => item[0] === "2.408" && item[1] === "38.8");
// position will be 0

findIndex lets you define a custom test function—here, we check if both elements of the nested array match your target values exactly.

2. Stringify arrays for comparison (use with caution)

If your nested arrays don't contain values that break JSON serialization (like functions or undefined), you can convert arrays to strings and compare those:

var target = JSON.stringify(["2.408","38.8"]);
var position = points.findIndex(item => JSON.stringify(item) === target);
// position will be 0

Just keep in mind this can fail if your array elements have special characters or non-serializable values, so the first method is usually the safer bet.

Quick Recap

  • Arrays are reference types—=== and indexOf check for identical object references, not matching content.
  • To find nested arrays by their content, use findIndex with a custom comparison function.

内容的提问来源于stack exchange,提问作者Tengda Su

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:02:35