English 中文(简体)
更新时出错:无法定义长度超过不可写数组末尾的数组索引属性
原标题:Error when Updating : can t define array index property past the end of an array with non-writable length

当我没有将数据保存到数据库时,我可以添加或删除,一旦保存了数据并且我想通过删除它们或添加新值进行更新,就会出现此错误无法定义超过不可写长度的数组末尾的数组索引属性。如何解决此问题?

  const handleDeleteDepartment = (companyIndex, departmentIndex) => {
    if (departmentIndex !== 0) {
      const newCompanies = [...companies];
      newCompanies[companyIndex].children.splice(departmentIndex, 1);
      setCompanies(newCompanies);
    }
  };
问题回答

在执行此行之前,您需要在此处进行更多检查:

newCompanies[companyIndex].children.splice(departmentIndex, 1);
  1. you want to be sure that newCompanies[companyIndex] exists:
if(newCompanies[companyIndex])
  1. you want to be sure the departmentIndex is not higher than the newCompanies[companyIndex].children length:
departmentIndex < newCompanies[companyIndex]?.children.length
  1. you want to be sure that newCompanies[companyIndex].children is an array:
Array.isArray(newCompanies[companyIndex].children)

这不应该失败:

const handleDeleteDepartment = (companyIndex, departmentIndex) => {
  const newCompanies = [...companies];
  if (departmentIndex !== 0) {
    if (
      newCompanies[companyIndex] &&
      Array.isArray(newCompanies[companyIndex]?.children) &&
      departmentIndex < newCompanies[companyIndex]?.children?.length
    ) {
      newCompanies[companyIndex].children.splice(departmentIndex, 1);
      setCompanies(newCompanies);
    }
  }
};




相关问题
Why does splice return a string instead of an array?

I m trying to splice array two from the two-dimensional array arr. var one = ["a","b"]; var two = ["c","d"]; var thr = ["e","f"]; var arr = [one,two,thr]; Here are my two unsuccessful attempts:...

Splice arrays in NumPy?

I d like to perform a splice of sorts in NumPy. Let s say I have two arrays, a and b: >>> a array([[ 1, 10], [ 2, 20], [ 5, 30]]) >>> b array([[ 1, 11], [ 3, 31]...

array_splice with multidimensional arrays?

Okay so I m fairly new to PHP and I am currently experimenting with arrays. As an example, lets assume this is my array: $t1 = array ( "basicInfo" => array ( "The Sineps", "December 25,...

Funny behaviour of Array.splice()

I was experimenting with the splice() method in jconsole a = [1,2,3,4,5,6,7,8,9,10] 1,2,3,4,5,6,7,8,9,10 Here, a is a simple array from 1 to 10. b = [ a , b , c ] a,b,c And this is b a.splice(0, ...

热门标签