G
G
Gennady2017-04-19 08:06:40
PowerShell
Gennady, 2017-04-19 08:06:40

Why doesn't .indexOf() work?

Hi all!
Faced the following problem.
I have an array of strings and perform the following operations with them, for example:

$arr = @("sometext", "value1","somethingelse")
$temp = $arr -imatch "val"

the value1 gets into the $temp variable, as I want. After that, I try to find this element in the array and find out its index. This is where the problem is, the following commands give me "-1" (which means the element was not found)
$arr.indexOf($temp)
[array]::IndexOf($arr, $temp)

At the same time, both previous commands work out if you manually enter Value1 (well, or something else)
Colleagues, tell me what I'm doing wrong? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Puchao, 2017-04-20
@genana40

Comments
This method searches all elements of a one-dimensional arrayfor value. To determine whether value exists in array, the method performs equality comparisons by calling each element's Equals method until it finds a match. This means that if an element overrides Object.Equals(Object) that override's method is called.
PS > $arr[1].Equals($temp)
False
PS > $arr[1].Equals("$temp")
True
Therefore:
PS > $arr.indexOf("$temp")
1
PS > [array] ::IndexOf($arr, "$temp")
1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question