Javascript : How do I call the array index of the string? -
hello have problem when change string in order invoke array in javascript, please me,
i have had array:
var fruit=['apple','banana','orange'];
and have data string mysql:
example: var string = '0,2';
how display array of fruit
corresponds var string
?
(thanks help)
you have split()
string array of indexes instead of string of indexes :
var indexes = '0,2'.split(','); //use ',' char split string
now, have pick fruits values corresponding each index in new indexes array create before.
var res = []; //the new array contains new fruits indexes.foreach(function(index) { //loop on fruit indexes want res.push(fruit[index]); //add juicy fruit :) });
and got new array (res
) juicy fruits :)
jsfiddle
edit:
or, shorter/nicer solution (thanks xotic750) (the second argument of map function specify context (this))
var ids = '0,2'; var fruits = ['apple','banana','orange']; fruits = ids.split(',').map(function(index) { return this[index]; }, fruits);
Comments
Post a Comment