var data = {
id: 1,
items: [
{id: 2},
{id: 3, items: [
{id: 4},
{id: 5}
]}
]
}
function extractIds(data){
var arr = [];
if(data.id){
arr.push(data.id);
}
if(data.items){
for(var i in data.items){
var subData = extractIds(data.items[i]);
for(var j in subData){
arr.push(subData[j]);
}
}
}
return arr ;
}
console.log(extractIds(data)); // should return [1,2,3,4,5]
矩阵求和
function matrixAddition(a, b){
var c = [] ;
for(var i in a){
c[i] = [];
for(var j in a[i]){
c[i][j] = a[i][j] + b[i][j]
}
}
return c
}
console.log(matrixAddition( [ [1, 2, 3], [3, 2, 1,], [1, 1, 1] ], [ [2, 2, 1], [3, 2, 3], [1, 1, 3] ] ));