Following Problem:
I have a Array:
var klassen = new Array();
klassen[0] = new Object();
klassen[0]["class"] = "barbarian";
klassen[0]["con"] = "0";
klassen[0]["str"] = "0";
klassen[1] = new Object();
klassen[1]["class"] = "bard";
klassen[1]["chr"] = "0";
klassen[1]["dex"] = "0"; '''
And i have a function:
function changecs(){
let csclass = document.getElementById("class")
window.finden = csclass.value;
alert(finden);
highlight();
}
function highlight(){
alert(finden);
let indexzahl = klassen.indexOf('finden')
alert (indexzahl);
}
This function is linked to a Html select ( i included the necessary:
<div id="class-frm">
<label for="class">Choose a Class</label>
<select id="class" onchange="changecs()">
<option id="default" value="default"> Optional </option>
<option id="barbarian" value="barbarian"> Barbarian </option>
<option id="bard" value="bard"> Bard </option>
My goal is it, to select something for example bard. Then i want to know the index number of "bard" which would be 1 in this example. I hope this is precise enough. Thanks!
for(let i=0; i<klassen.length; i++){
const element = klassen[i];
const keys = Object.keys(element);
keys.forEach(key => {
if(element[key] === 'bard'){
console.log(klassen.indexOf(element))
}
});
// you can use a flag and break here
}
Use Array.prototype.fineIndex()
:
const klassen = [{'class': 'barbarian', con: 0, str: 0}, {'class': 'bard', chr: 0, dex: 0}] function changecs({target:{value}}){ const itemPosition = klassen.findIndex(item => item.class == value) console.log(itemPosition) }
<label for="class">Choose a Class</label> <select id="class" onchange="changecs(event)"> <option id="default" value="default"> Optional </option> <option id="barbarian" value="barbarian"> Barbarian </option> <option id="bard" value="bard"> Bard </option> </select>
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.