js数组操作

let arr = [
{age:18,name:a}
{age:13,name:b}
{age:18,name:c}
{age:4,name:e}
]
遍历arr数组,如果age是18,把当前这个数据name字段加入当前数据后面
最后结果是这样:

let arr = [
{age:18,name:a}
{name:a}
{age:13,name:b}
{age:18,name:c}
{name:c}
{age:4,name:e}
]

回答

arr.reduce((res, item) => {

res.push(item)

item.age == 18 && res.push({name: item.name})

return res

}, [])

提问之前麻烦自己先检查一下自己提出的问题

image.png

image.png

var arr5 = [

{age:18,name:'a'},

{age:13,name:'b'},

{age:18,name:'c'},

{age:4,name:'e'},

]

for(let i = 0;i<arr5.length;i++){

if(arr5[i].age == 18){

let obj = {name:arr5[i].name}

arr5.splice(i+1,0,obj)

}

}

console.log('这是什么?',arr5)

以上是 js数组操作 的全部内容, 来源链接: utcz.com/a/28186.html

回到顶部