为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以通过指定索引数组来访问数组的第 n 个深度元素?

是否可以通过指定索引数组来访问数组的第 n 个深度元素?

MMTTMM 2022-08-27 09:25:27
更新谢谢大家的投入,感谢你们,我现在意识到我对JS做了一个严重错误的假设。实际上,如果修改它,下面提供的代码可以正常工作:...  let currentPlaceInArray;  for (let i = 0; i < position.length; i++) {    let place = position[i];    if (i + 1 === position.length) return currentPlaceInArray[place] = content; // Added this line now    /***Explanation:    Without this added line, the currentPlaceInArray variable is reassigned in the end     to 'needle' in the present example. Thus, assigning it to something else (like    currentPlaceInArray = ['updated']) will not have any effect on the array, because    currentPlaceInArray is not assigned to it anymore, it's assigned to the string 'needle'    ***/    currentPlaceInArray = currentPlaceInArray ? currentPlaceInArray[place] : myArray[place];   }原始问题我有一个大型非结构化多维数组,我不知道它有多少嵌套数组,它们具有不同的长度,就像这个简化的例子一样:var myArray =[  [    [],[]  ],  [    [],[],[],[]  ],  [    [],    [      [        ['needle']      ]    ]  ]];我希望能够更新到其他内容。这可以通过执行'needle'myArray[2][1][0][0] = 'updated';我想创建一个函数,它只接受2条信息作为参数:1)要编写的字符串和2)一个数组,其中包含要更新的数组项的位置。在上面的情况下,它将被称为:。myArraychangeNeedle('updated', [2, 1, 0, 0])但是,我不能将变量分配给数组键,只能分配给其值。如果可以将变量分配给数组键,我可以用当前位置更新该变量(即,var currentPosition将是myArray[x],而currentPosition[y]将是myArray[x][y]) [更新:它是完全相反的,将变量分配给数组将精确指向该数组,所以]。这样:currentPosition[y] === myArray[x][y]function changeNeedle(content, position) {  /***  content: a string  position: an array, with the position of the item in myArray to be updated  ***/  let currentPlaceInArray;  for (let i = 0; i < position.length; i++) {    let place = position[i];    currentPlaceInArray = currentPlaceInArray ? currentPlaceInArray[place] : myArray[place];   }  currentPlaceInArray = content;}是否可以在不使用 的情况下实现此函数, 窗口.Function() 还是将原型添加到数组中?changeNeedleeval
查看完整描述

4 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

起初,Chase的答案似乎是正确的(使用递归),但似乎您希望您的代码仅遵循提供给函数的路径。


如果您确定要更改的元素的位置,您仍然可以使用递归方法:


纯 JS 递归解决方案

var myArray = [

  [

    [],

    []

  ],

  [

    [],

    [],

    [],

    []

  ],

  [

    [],

    [

      [

        ['needle']

      ]

    ]

  ]

];


function changeNeedle(arr, content, position) {


  // removes first element of position and assign to curPos

  let curPos = position.shift();


  // optional: throw error if position has nothing

  // it will throw an undefined error anyway, so it might be a good idea

  if (!arr[curPos])

    throw new Error("Nothing in specified position");


  if (!position.length) {

    // finished iterating through positions, so populate it

    arr[curPos] = content;

  } else {

    // passes the new level array and remaining position steps

    changeNeedle(arr[curPos], content, position);

  }


}


// alters the specified position

changeNeedle(myArray, 'I just got changed', [2, 1, 0, 0]);


console.log(myArray);


但是,如果要搜索与内容对应的元素,仍必须循环访问每个元素。

查看完整回答
反对 回复 2022-08-27
?
largeQ

TA贡献2039条经验 获得超8个赞

如果要避免导入库,则具有就地更新的特定于阵列的解决方案将如下所示:


function changeNeedle(searchValue, replaceWith, inputArray=myArray) {

  inputArray.forEach((v, idx) => {

    if (v === searchValue) {

      inputArray[idx] = replaceWith;

    } else if (Array.isArray(v)) {

      changeNeedle(searchValue, replaceWith, v);

    }

  });

  return inputArray;

}

然后,您可以调用,并且您的值将被更改以将 的实例更改为 。changeNeedle('needle', 'pickle', myArray);myArrayneedlepickle


返回值,然后如下所示:myArray


JSON.stringify(myArray, null, 4);

[

    [

        [],

        []

    ],

    [

        [],

        [],

        [],

        []

    ],

    [

        [],

        [

            [

                [

                    "pickle"

                ]

            ]

        ]

    ]

]

更新:根据您的回复,遵循已知更新的确切路径的非递归解决方案。


function changeNeedle(newValue, atPositions = [0], mutateArray = myArray) {

  let target = mutateArray;

  atPositions.forEach((targetPos, idx) => {

    if (idx >= atPositions.length - 1) {

      target[targetPos] = newValue;

    } else {

        target = target[targetPos];

    }

  });

  return mutateArray;

}

请参见:https://jsfiddle.net/y0365dng/


查看完整回答
反对 回复 2022-08-27
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

我建议考虑经过充分测试的Lodash函数更新(或设置,等等)。我认为这非常接近你所需要的。


查看完整回答
反对 回复 2022-08-27
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

不,你不能。


执行此操作的最简单方法是存储要修改的数组 () 和键 ()。然后,您只需要进行常规分配,例如.array = myArray[2][1][0]index = 0array[index] = value


您可以考虑以下实现:


function changeNeedle(value, keys) {

  let target = array;


  for (const i of keys.slice(0, -1)) {

    target = target[i];

  }


  target[keys[keys.length - 1]] = value;

}


查看完整回答
反对 回复 2022-08-27
  • 4 回答
  • 0 关注
  • 212 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号