As far as I understand, the indexOf
method uses strict equality which in my mind means that if I have an object
animal = {id: 1, name: 'bison'}
the statement
animal.name === 'bison'
would be true which it is.
What I don't understand is why indexOf
in the below example will return an index for both "bison" and "bison_ox" which in my mind means that it does not follow strict equality, or am I missing something?
const beasts = ['bison', 'camel', 'duck', 'bison_ox'];
const tmp = [{id: 1, name: 'bison'}, {id: 2, name: 'camel'}, {id: 3, name: 'duck'}, {id: 4, name: 'bison_ox'}]
// Expected output: 1
for(let i = 0; i< beasts.length; i++) {
tmp.forEach(item => {
if(beasts[i].indexOf(item.name) !== -1) {
console.log('index: ' + i + ' item: ' + item.name + ' beast: ' + beasts[i])
}
})
}
gives the following output
> "index: 0 item: bison beast: bison"
> "index: 1 item: camel beast: camel"
> "index: 2 item: duck beast: duck"
> "index: 3 item: bison beast: bison_ox"
> "index: 3 item: bison_ox beast: bison_ox"
why does indexOf
get the first index ("bison") when the searchElement
is "bison_ox"?
To quote MDN:
The indexOf() method of
String
values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
When testing where "bison" appears in "bison_ox", you can see it appears at the beginning of the string, i.e., the index 0.
If you want to use equality, just use the equality operator, not indexOf
:
const beasts = ['bison', 'camel', 'duck', 'bison_ox'];
const tmp = [{id: 1, name: 'bison'}, {id: 2, name: 'camel'}, {id: 3, name: 'duck'}, {id: 4, name: 'bison_ox'}]
// Expected output: 1
for(let i = 0; i< beasts.length; i++) {
tmp.forEach(item => {
if(beasts[i] === item.name) { // HERE!
console.log('index: ' + i + ' item: ' + item.name + ' beast: ' + beasts[i])
}
})
}