我将值推入forEach循环内的数组中。当我在循环外调用数组时,得到以下值:
d.data:
[{hello: 'abc', asd: '123', fgh: '345' }]
[{sdfg: '123', yo: 'ghj', fgh: '345' }]
[{gd: '123', asd: '123', bonjour: 'yui' }]
[{hello: '123', asd: '567', fgh: '345' }]
forEach循环:
let str_arr = [];
d.data.forEach(recs => {
each_keys = Object.keys(recs);
each_vals = Object.values(recs);
each_vals.forEach(k => {
if (typeof k == 'string') {
find_key = Object.keys(recs).find(key => recs[key] === k);
str_arr.push(find_key);
}
});
});
str_arr:
["hello", "hello", "hello"]
["yo", "yo", "yo"]
["bonjour", "bonjour", "bonjour"]
[]
console.log(typeof str_arr[0] + ' = ' + str_arr[0]
结果:
string = hello
string = yo
string = bonjour
undefined = undefined
我想将所有str_arr [0]推入一个数组中,所以我这样做吗?
let string_array = [];
if (str_arr[0] !== undefined) {
string_array.push(str_arr[0]);
}
console.log(string_array);
我的结果是:
hello
yo
string
(empty)
为什么我仍然在结果中得到未定义的值?
最佳答案
input_arr = [
["hello", "hello", "hello"],
["yo", "yo", "yo"],
["bonjour", "bonjour", "bonjour"],
[]
];
let output_array = [];
input_arr.forEach(element => {
if (element[0] !== undefined) {
output_array.push(element[0]);
}
});
console.log(output_array);
console.log(input_arr[3][0] !== undefined); // works as expected