简体   繁体   中英

Using indexOf() in Javascript array

I have an array like this [HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"] . I got this from console.

I trying to find out value like below

var sku = skus_colorcode.indexOf('9620');                   
console.log(sku);

But it is returning -1.

Why I am getting this result ??

You code is not valid at all. An array is a list of elements, without keys. You must use an object, like this :

var skus_colorcode = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"}

To find the key (HT....) that corresponds to "9620", try this code :

var keys = Object.getOwnPropertyNames(skus_colorcode), key;

for(var i = 0; i < keys.length; i++)
    if(skus_colorcode[keys[i]] === "9620") {
        key = keys[i];
        break;
    }

// The right key is into the "key" variable
console.log(key); // says "HT2787Z2UK"

Try this

function arraySearch(arr,val) {
    for (var key in arr) {
        this_val = array[key];
        if(this_val == val){
            return key;
            break;
        }
    }
 }

This should be

   var obj = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"}

for (var key of obj) {
  if (obj[key] == "9620"){
     return key;
  }
}

return false

I agree with "hemnath mouli" code should be like as he wrote:

<script type="text/javascript">
    keys = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"};
    function getIndexOf(obj,value){
        var count = 0;
        for (var i in obj){
            if(obj[i] == value.toString()){
                return  "index[" + count + "]:" + obj[i]  + " = " + i;
                //return what you want
            }
            count ++;
        }
    }
</script>

Then U got the values

<script type="text/javascript">
    alert(getIndexOf(keys,9621));
</script>

Could you please send a piece of code to retrieve the values @ClementNerma even I agree with you this is not the more efficient way.

I just do not want to "downvote" the question.

Or if you want to convert your Object to an Array:

<script type="text/javascript">
    keys = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"};
    function obj2Array(obj){
        k = [];
        for (var i in obj){
            k.push(obj[i]);
        }
        return k;
    }
</script>

<script type="text/javascript">
    arr = obj2Array(keys);
    alert (arr[2]);
</script>

@abu abu

You can use Jquery:

var skus_colorcode = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"}


$.each( skus_colorcode , function( key, value ) {
   if(value == '9620')
       alert(key);
});

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