javascript - Issues about loop traversal of arrays
给我你的怀抱
给我你的怀抱 2017-06-26 10:55:17
0
6
833
[{
    id: '1',
    name: '小王',
    desc: '小王描述'
}, {
    id: '2',
    name: '小强',
    desc: '小强描述'
}, {
    id: '6',
    name: '小红',
    desc: '小红描述'
}, {
    id: '9',
    name: '小东',
    desc: '小东描述'
}]

This is the data sent back from the background. How can I use a for loop to turn the id inside into a number? I don’t know how to write it, so embarrassed

给我你的怀抱
给我你的怀抱

reply all(6)
过去多啦不再A梦

The key point is to convert the string into a numerical value, either parseInt or Number can be converted. Or let the background pass the numerical type directly. Question: This is data obtained from the backend and is generally rendered to the page. Why does it need to be converted into a numerical value?

Peter_Zhu

Like this

function change(items){
    items= items|| [];
    for( var i = 0,item; item = items[i++]; ){
        item.id *= 1;
    }
    return items;
}

var result = change(/*你需要弄的*/);
刘奇
//方法一
for(var i=0,len=arr.length;i<len;i++){
arr[i].id=parseInt(arr[i].id)
}
//方法二
arr.map(function(item){return {desc:item.desc,id:parseInt(item.id),name:item.name}})
//es6写法
arr.map(item=>{{desc:item.desc,id:parseInt(item.id),name:item.name}})
代言
var result = arr.map(item => {item.id = parseInt(item.id); return item;});

But because of the object reference type, the id in the original array arr is also a numeric value

迷茫

Just use parseInt to transfer directly and it will be ok

学习ing

Let’s talk about the idea first:
1. First traverse the array
2. Traverse the object
3. Add attribute key-value pairs and delete old key-value pairs

Code below:

        var jsonData = [{
            id: '1',
            name: '小王',
            desc: '小王描述'
        }, {
            id: '2',
            name: '小强',
            desc: '小强描述'
        }, {
            id: '6',
            name: '小红',
            desc: '小红描述'
        }, {
            id: '9',
            name: '小东',
            desc: '小东描述'
        }];
        var i = 0;
        for (; i < jsonData.length; i++) {
            for (var name in jsonData[i]) {
                if (name === 'id') {
                    jsonData[i][i] = jsonData[i][name];
                    delete jsonData[i][name];
                }
            }
        }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template