admin管理员组

文章数量:1278985

 var array = [{"one":1, "two":2},{"one":3, "two":4}];

            var result = array.findIndex(function (value) {
                if (value === 2) {
                    return false;
                }
                return true;
            });

            console.log(result); 

i keep getting '0' in the console. how should i change (value ===2) ? i have tried change to (value === {"two":2}) but still return '0'.

is there any other array method that suitable ?

 var array = [{"one":1, "two":2},{"one":3, "two":4}];

            var result = array.findIndex(function (value) {
                if (value === 2) {
                    return false;
                }
                return true;
            });

            console.log(result); 

i keep getting '0' in the console. how should i change (value ===2) ? i have tried change to (value === {"two":2}) but still return '0'.

is there any other array method that suitable ?

Share Improve this question edited Jun 6, 2017 at 6:50 Zachary Lordford asked Jun 6, 2017 at 6:47 Zachary LordfordZachary Lordford 1463 gold badges5 silver badges17 bronze badges 9
  • 2 Because you are doing return true in every case. Also what does value === 2 means. value will be an object – Rajesh Commented Jun 6, 2017 at 6:49
  • which property do you like to check? there is no valuein the array. – Nina Scholz Commented Jun 6, 2017 at 6:49
  • 1 value will never be 2 it will be either {"one":1, "two":2} or {"one":3, "two":4} – Jaromanda X Commented Jun 6, 2017 at 6:50
  • 1 put a console.log into your findindex callback before the if()..and print the value passed to the callback. You might get some understanding as to what you the value is and what you are checking it with. – Yogesh Patil Commented Jun 6, 2017 at 6:52
  • @JaromandaX i just want the index of {"one":1, "two":2} to show how should i change if (value === 2) ? – Zachary Lordford Commented Jun 6, 2017 at 6:53
 |  Show 4 more ments

2 Answers 2

Reset to default 10

You need to check one of the properties of the objects of the array. Then return the result of the check.

var array = [{ one: 1, two: 2 }, { one: 3, two: 4 }],
    result = array.findIndex(function(object) {
        return object.two === 2;
    });

console.log(result);

Its first argument of the array .change with value.two .its object property not a array

var array = [{"one":1, "two":2},{"one":3, "two":4}];
            var result = array.findIndex(function (value) {
                               return value.two == 2;
            });
            console.log(result); 

本文标签: findIndex() javascript array objectStack Overflow