foreach、for、for in循环方式

本文通过具体示例,介绍了如何使用JavaScript遍历数组和对象,包括使用forEach进行数组遍历,for...in进行对象遍历,以及传统for循环的使用。同时,展示了如何在遍历过程中修改数组中对象的属性。
$(function(){
var data1 =
[
{
id:'126652',
no: '1',
longitude: '103.94292',
latitude: '30.620123',
distance:'253'
}, {
id:'122855',
no: '2',
longitude: '103.94292',
latitude: '30.620123',
distance:'258.25'
}, {
id:'1285569',
no: '3',
longitude: '103.94292',
latitude: '30.620123',
distance:'253'
}, {
id:'1222555',
no: '4',
longitude: '103.94292',
latitude: '30.620123',
distance:'253'
}]

//遍历数组而设计
data1.forEach(function (val,index,arr) {
console.log(val) //{id: "126652", no: "1", longitude: "103.94292", latitude: "30.620123", distance: "253"}
console.log(val.no);//1 2 3 4
console.log(index);//0 1 2 3
console.log(arr);//整个数组
})
var data2 = {a:'1',b:'2',c:'3',d:'4'}
//循环对象而设计
for(let i in data2){
console.log(i)//a b c d
console.log(data2[i])//1 2 3 4
}
var data3 = [1,2,3,4]
//最原始遍历方式
for(var i=0;i<data3.length;i++){
console.log(data3[i])//1 2 3 4
}
})




//修改某一条对象数据值
var stooges = [
 2   {label: 1, value: 1, placeCode: 'sh', stock_code: 40},
 3   {label: 1, value: 1, placeCode: 'sh', stock_code: 50},
 4   {label: 1, value: 1, placeCode: 'sz', stock_code: 60, status: 1},
 5   {label: 1, value: 1, placeCode: 'sz', stock_code: 39, status: 1}
 6 ];
 7 
 8 for (var i = 0; i < stooges.length; i++) {
 9   var item = stooges[i];
10   if (item.placeCode == "sh") {
11     item.placeCode = "沪";
12   }
13   if (item.placeCode == "sz") {
14     item.placeCode = "深";
15   }
16 }
17 写个for循环遍历一下,从第一个对象开始,发现对应的placeCode是sh则更新成文字沪,发现对应的placeCode是sz则更新成文字深,一直到最后一个对象

转载于:https://www.cnblogs.com/yixiaoyang-/p/9989831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值