playing around with foreach fuction atm, and trying to get .data out of it.
JavaScript
x
12
12
1
const foreachfunc = (data = null) => {
2
data.forEach((element, index) => {
3
console.log('element = ' + element, 'index = ' + index)
4
let head = element.head
5
console.log(head)
6
});
7
};
8
9
const myarray = ["test1", "test2"]
10
11
foreachfunc(myarray)
12
okay so right now it outputs:
JavaScript
1
5
1
element = test1 index = 0
2
undefined
3
element = test2 index = 1
4
undefined
5
and it does makes sense since i haven’t giving ‘head’ any data yet. But is it possible to give ‘head’ data within ‘myarray’?
Advertisement
Answer
Problem is with your array as it does not contain data that you are trying to access. check updated code below
JavaScript
1
12
12
1
const foreachfunc = (data = null) => {
2
data.forEach((element, index) => {
3
console.log('element = ' + element.text, 'index = ' + index)
4
let head = element.head
5
console.log(head)
6
});
7
};
8
9
const myarray = [{head:"head1",text:"text1"},{head:"head2",text:"text2"}]
10
11
foreachfunc(myarray)
12