繁体   English   中英

Javascript通过将字符串值与数组进行比较来获取数组的索引值

[英]Javascript Get index value of array by comparing string value to array

我读的文本框,并试图比较值的数组,并获得索引值,但由于某些原因,我不能让过去这个TypeError: ar[z] is undefined ,即使我能错误console.log使用的数值就前一行。

   //get name from textbox
    var name= document.getElementById("name");
     var name= name.value;

     //remove everything before name
    var index = name.toString().split(":");
    var index = index[1];

    //get product data to array
    var ar = JSON.parse( '<?php echo json_encode($productlist) ?>' );
    var nameslist= [];
    var z = 0;


   //this gives out an value
console.log(ar[0]['product_name']);

 //push 10 names to one list
////HERE IS THE ERROR: typeError: ar[z] is undefined

    while(z < 10){
     nameslist.push(ar[z]['product_name']);

      z++;
      }

    //Get the index value of name that matched the one from textbox
    var a = nameslist.indexOf(index); 
    console.log(a);

您可能要尝试以下操作:

var l = ar.length <= 10 ? ar.length : 10;
while(z < l) {
    nameslist.push(ar[z]['product_name']);
    z++;
}

用于

//get product data to array
var ar = [{'product_name':"P1"},{"product_name":"P2"}]
var nameslist = [];
var z = 0;

console.log(ar[0]['product_name']);

 //push 10 names to one list
////HERE IS THE ERROR: typeError: ar[z] is undefined

 for(i=0;i<ar.length;i++)
 {
    nameslist.push(ar[i]['product_name']) 
 }

console.log(nameslist);

使用Jquery可以轻松完成。

if ($.inArray(value, myvalueArr) > -1) {
    alert($.inArray(value, myvalueArr);)                       
}

这将为您提供与值匹配的数组中的索引

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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