簡體   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