javascript loop array problem
阿神
阿神 2017-05-19 10:29:52
0
3
508
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
怎么循环出arr 的id?
循环出来后,修改这些id的值了,再怎么存回去?
阿神
阿神

闭关修行中......

reply all(3)
给我你的怀抱

Put it back after changing:

var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]

console.log("原始数组:",JSON.stringify(arr)) // 原始数组
arr = arr.map(function(i){
   return Object.assign(i , { id:10086} ) // 你这里想怎么修改,就怎么修改。 
});
console.log("新数组:",JSON.stringify(arr)) // 新数组id已经变了。

Traverse the array:

// 第一种
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
console.log(arr.map((i) => i.id))

// 第二种
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
arr.map((i) => {
    console.log(i.id)
})

// 第三种
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
arr.forEach((i) => {
    console.log(i.id)
})

// 第四种
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
for(var i=0,l=arr.length;i<l;){
    console.log(arr[i++].id)
}

// 第五种
var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
for(var i in arr){ console.log(arr[i].id) }
Ty80

var arr =[{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}]
How to loop The IDs of arr?
After the loop is released, the values ​​of these IDs are modified. How to save them back?


Personally I highly recommend forEach map These are more functional ways of writing

function arrGenerator(){
    // return 原数组; 
    return [{"id":1,"name":2},{"id":3,"name":4},{"id":3,"name":2}];  
}


var arr = arrGenerator(); 
var res = arr.map(item => item.id * 2); // 这里处理id 把原数组映射成另外个数组 
// => 
// [2, 6, 6]

var arr2 = arrGenerator(); 
var res2 = arr2.map(item => {
    return {
        id: item.id * 2, // 这里处理 id
        name: item.name + '酱❤❤'
    }
}); 

Operations on arrays are the same as set mapping

Especially this one. . . It’s so intoxicating
arr.map(item => item.id * 2)

曾经蜡笔没有小新

The easy-to-understand method is to directly loop and then make a judgment based on the id you want to change and then reassign it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template