如何通过这个数组循环,我想循环和和名称值添加到空数组,当我安慰.LOG它给下面的结果,你可以请大家帮忙,我的代码的结果是空数组
this.props.names它显示
(3)[{...},{...},{...}] 0:{名称: “ABC”,ID:1} 1:{名称: “DEF”,ID:2} 2:{名称: “GH” ,ID:3}长度:3原:阵列(0)
let titles = []
let cats = []
cats = this.props.names
let len = this.props.names.length;
for( i = 0 ;i< cats.length ; i++){
titles.push(cats[i].id)
}
return titles;
从我看到...做
let titles = []
let cats = [{name: "abc", id: 1},{name: "def", id: 2},{name: "gh", id: 3}]
for( var p = 0 ;p< cats.length ; p++){
titles.push(cats[p].id)
}
console.log(titles)
如果你只是想提取的ID,以及道具和/或名称可能为空或null,则可以使用map
做到这一点:
const titles = (props && props.names || []).map(val => val.id);
这里props && props.names || []
将等于[]
如果props
或props.names
计算结果为falsy。这样的话,你仍然可以申请map
它,这将在这种情况下返回一个空数组。
function demo(props) {
const titles = (props && props.names || []).map(val => val.id);
console.log(titles);
}
demo({ names: [{name: 'one', id: 1}, {name: 'two', id: 2}, {name: 'three', id: 3}] });
demo({ names: [] });
demo({});
demo(null);