I am reading a textbox and trying to compare the value to array and get the index value, but for some reason I can not get past this TypeError: ar[z] is undefined
error even though I can console.log
it using numeric value on previous line.
//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);
You may want to try this:
var l = ar.length <= 10 ? ar.length : 10;
while(z < l) {
nameslist.push(ar[z]['product_name']);
z++;
}
use a 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);
It can be easily done using Jquery.
if ($.inArray(value, myvalueArr) > -1) {
alert($.inArray(value, myvalueArr);)
}
This will give you the index in array with which the value was matched
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.