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

时间:2014-10-17 10:38:53

标签: javascript arrays

我正在阅读文本框并尝试将值与数组进行比较并获取索引值,但出于某种原因,我无法通过此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);

3 个答案:

答案 0 :(得分:0)

你可能想试试这个:

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

答案 1 :(得分:0)

使用for

//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);

答案 2 :(得分:0)

可以使用Jquery轻松完成。

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

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