I am currently using .append to join two or more arrays together to form a phrase as you can see in this jsfiddle: jsfiddle append array.
function P1(phrase) {
var sen = ('<a class="senword">' + phrase[0] + '<br/>' + phrase[1] + ' </a>');
return sen;
}
var words = [
['one', '一'],
['eight','八'],
['hundred','百'],
];
$("#onehundred").append(P1(words[0])).append(P1(words[2]));
$("#eighthundred").append(P1(words[1])).append(P1(words[2]));
However I need a way to append arrays by using an array value, e.g. ‘hundred’ instead of the index number e.g. [2]. This is because each time I add new vocabulary to the ‘words’ array, the index number is obviously changing, which means I would need to manually change all the index numbers for the phrases.
So is there a way to join arrays by using a value instead of an index number, as this value wouldn’t change no matter how many new words I added?
For example instead of:
$("#onehundred").append(P1(words[0])).append(P1(words[2]));
Have something like this (but obviously this is not correct):
$("#onehundred").append(P1(words['one'])).append(P1(words['hundred']));
PS
I don’t mind changing to a literal array if it helps, e.g.:
var words = [
{'english':'hundred', 'chinese':'百'},
];
Thanks for any suggestions!
Change your data structure to an object:
Then change your
P1function to accept the property name, and have it do the look-up…And then just pass the property name…
DEMO: http://jsfiddle.net/DgAzz/
If you can’t change the initial structure, then create the object from it…
DEMO: http://jsfiddle.net/DgAzz/1/