简体   繁体   中英

How to test reference equality in Javascript?

I have an array containing references to various objects.
The only guarantee I have is that the array does not contain multiple references to the same object.
Specifically, I am not guaranteed that the objects' contents are different.

There is another piece of code which gives me a reference to some object, obj .
I need to test if obj is the last item in my array, and if this is true, and obj satisfies some additional requirements, I want to call pop on my array.

How do I test if obj was the last item in my array?

In JavaScript, === (and, actually, == ) with object references tests reference equality (eg, that they refer to the same object).

So to handle the requirement

There is another piece of code which gives me a reference to some object, obj. I need to test if obj is the last item in my array

...then:

if (obj === array[array.length-1]) {
    // It's the same object
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM