javascript JS中的While循环获取文件夹路径

ct3nt3jp  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(106)

我尝试在JS中使用while循环,但是我对JS语法不太了解。每次我测试下面的代码时,我都会得到一个错误“内存不足”,所以我想我需要修复代码,但是找不到不工作的地方

const template = [
    {title: 'template 1', parentFolder:'', uniqueid: '1'},
    {title: 'template 2-2', parentFolder:'', uniqueid: '22'},
    {title: 'template 2-2', parentFolder:'', uniqueid: '222'},
    {title: 'template 2-2-1', parentFolder:'', uniqueid: '333'},
];

template[0].parentFolder = template[0];
template[1].parentFolder = template[0];
template[2].parentFolder = template[0];
template[3].parentFolder = template[1];

// Function and get the folder to start from
function getFoldersPath(currentFolder) {

  // Create an empty list to hold the full path
  const previousParents = [];

  // Add each parentFolder to the list until reaching the root parent

  while (currentFolder.uniqueid !== template[0].uniqueid) {
    previousParents.push(currentFolder.uniqueid);
    currentFolder = currentFolder.parentFolder.uniqueid;
  }
  return previousParents;
}

var result = getFoldersPath(template[3])
console.log(result)

如果有人能帮我修复代码

rsaldnfx

rsaldnfx1#

代码内存不足的原因是while循环的条件,它没有正确地根据根父文件夹的唯一ID检查当前文件夹的唯一ID。
在while循环中,条件“currentFolder.uniqueid”!== template[0].uniqueid始终为true,因为它将字符串文字“currentFolder.uniqueid”与根父文件夹的唯一ID进行比较。它不是检查当前文件夹的uniqueid属性的值,而是检查字符串“currentFolder.uniqueid”本身。

// Function and get the folder to start from
function getFoldersPath(currentFolder) {
  // Create an empty list to hold the full path
  const previousParents = [];

  // Add each parentFolder to the list until reaching the root parent
  while (currentFolder.uniqueid !== template[0].uniqueid) {
    previousParents.push(currentFolder.uniqueid);
    currentFolder = currentFolder.parentFolder;
  }
  return previousParents;
}

var result = getFoldersPath(template[3])
console.log(result)

相关问题