我花了整晚的時間研究這個問題,我知道答案很接近;但我仍然有很多語法工作要做。請不要低估這一點 - 這樣做只會阻止像我這樣的新手提問。 我需要創建一個接受簡單對象作爲參數的函數,並返回一個數組數組。函數應該在具有任意數量的屬性列的對象上使用簡單的字符串/數字值。我將展示並解釋代碼我的工作,我會在下面附上:JavaScript遍歷對象將數組追加到數組
//my first code:
var hi = {a: 1, b: 2, c: 3};
var props = new Array([],[],[]);
var lent = 0;
function newWave(hi){
for(var key in hi){
props[lent].push(key);
props[lent].push(hi[key]);
lent = lent + 1;
}
return props;
}
newWave(hi);
//function yields: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
//The return output is correct, but I need a universal code;
//looking at the number of columns in variable 'props', you can
//tell that this function only works on objects with 3 roperties.
//My second code:
function newWave(hi) {
var props = [];
var outcome = [];
for (var i = 0; i<1; i++){
for(var key in hi){
props.push(key, hi[key]);
outcome.push(props);
}
return outcome;
}
}
newWave(hi);
//This returns:
//[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ],
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ],
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
//I feel like the answer is so close, but it's been 7 hours working on this,
//your help is greatly appreciated
Didn't瞭解項目的方法,很好 – juvian
優秀的快捷方式,但對於這項任務, '迴歸' 是必需的,而不是CONSOLE.LOG。它必須在功能的傳統輪廓中。 – Joan