3 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以編寫 find 數(shù)組以根據(jù)您的焦點(diǎn)數(shù)組獲取數(shù)組。使用數(shù)組方法reduce從索引數(shù)組中查找節(jié)點(diǎn)
var updateNode = focus.reduce((node,index) => node && node[index], notes);
updateNode && updateNode.push("new content");

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用 for 循環(huán)來實(shí)現(xiàn)。
let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
myArray = myArray[currentFocusedArray[i]]
}
在此之后,您將myArray引用 的深層嵌套值rootArray。
let rootArray = {
"1": {
"2": []
}
}
let currentFocusedArray = [1, 2]
let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
myArray = myArray[currentFocusedArray[i]]
}
myArray.push("new content")
console.log(myArray)

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用reduce創(chuàng)建這樣的函數(shù)來在任何級(jí)別設(shè)置嵌套數(shù)組元素。
const rootArray = []
function set(arr, index, value) {
index.reduce((r, e, i, a) => {
if (!r[e]) {
if (a[i + 1]) r[e] = []
} else if (!Array.isArray(r[e])) {
if (a[i + 1]) {
r[e] = [r[e]]
}
}
if (!a[i + 1]) {
if (Array.isArray(r)) {
r[e] = value
}
}
return r[e]
}, arr)
}
set(rootArray, [1, 2], 'foo');
set(rootArray, [1, 1, 2], 'bar');
set(rootArray, [1, 2, 2], 'baz');
console.log(JSON.stringify(rootArray))
添加回答
舉報(bào)