我要根据state分组,然后报错了。
var json = [
{"state": 0, "name": "xxxx"},
{"state": 1, "name": "cccc"},
{"state": 2, "name": "zzzz"},
{"state": 3, "name": "hhhh"}
]
function sortjson(json){
var i,l,n,
a1 = [],a2=[],a3=[],a4=[];
for(i=0,l=json.length;i<l;i++){
switch( json[i].state){
case 0:
a1.push(json.splice(i,1))
break;
case 1:
a2.push(json.splice(i,1))
break;
case 2:
a3.push(json.splice(i,1))
break;
case 3:
a4.push(json.splice(i,1))
break;
}
}
return {
a1:a1,a2:a2,a3:a3,a4:a4
}
}
报错 Uncaught TypeError: Cannot read property 'state' of undefined
大家讲道理2017-04-10 13:14:48
因为每个 loop 都 splice 了初始数组,数组里的项越来越少。到第三次循环就 undefined,第四次就直接抛异常了。
你自己在 switch 之前 console.log(json, i)
对比下看看:
黄舟2017-04-10 13:14:48
Array.prototype.sortjson = function () {
[1,2,3,4].forEach(function(number){window['a'+number] = []});
this.forEach(function(item){window['a'+(item.state+1)].push(item)});
return {a1:a1, a2:a2, a3:a3, a4:a4};
}
console.log([
{"state": 0, "name": "xxxx"},
{"state": 1, "name": "cccc"},
{"state": 2, "name": "zzzz"},
{"state": 3, "name": "hhhh"}
].sortjson());
写完这段代码之后想起了今天同学给我讲的笑话:“难怪程序员找不到女朋友,因为他们都喜欢又精又快又短“,再此写上以博诸君一笑。