简体   繁体   English

突然未定义数组js

[英]suddenly undefined array js

I am messing with a genetic algorithm for curiosity. 我对遗传算法感到好奇。

I was doing the generation switch part when I hit a wall. 当我碰壁时,我正在做发电开关部分。 I removed the parents for the next generation from the previous actors array, pushed them in a parents array and was proceding to remove random parent pairs from the parents array and store them in progen1 and progen2 variables, but for some reason the inner array cromossomo of progen1 was undefined, event though I could access its elements when it progen1 whas stored in parents array. 我从以前的actor数组中删除了下一代的父级,将它们推到了parents数组中,并且正要从父级数组中删除随机的父对,并将它们存储在progen1和progen2变量中,但是由于某种原因progen1是未定义的,虽然我可以在progen1存储在父母数组中时访问它的元素。

This code: 这段代码:

var n1=Math.floor((Math.random(Math.floor(parents.length))));
console.log(parents[n1].cromossomo[0]);
var progen1=parents.splice(n1);
console.log(progen1.cromossomo[0]);
var n2=Math.floor((Math.random(Math.floor(parents.length))));
var progen2=parents.splice(n2);

produces: 生产:

{dx: -4.805923044269889, dy: -2.447397585132567}dx: -4.805923044269889dy: -2.447397585132567__proto__: Object
scripts.js:94 Uncaught TypeError: Cannot read property '0' of undefined
at switchGeneration (scripts.js:94)
at run (scripts.js:140)

and I am going crazy not knowing why this is happening! 我发疯了,不知道为什么会这样!

splice() returns an array of all the elements that were removed from the array. splice()返回从数组中删除的所有元素的数组。 So progen1 is an array of all the elements of parents starting from n1 , not a single object. 因此progen1是从n1开始的所有parents元素的数组,而不是单个对象。 The array doesn't have a cromossomo property, so progen1.cromossomo[0] tries to get the 0 index of undefined . 该数组没有cromossomo属性,因此progen1.cromossomo[0]尝试获取undefined0索引。

If your intent is to just remove 1 element from parents , you need to specify number of elements to remove when you call splice() . 如果您打算从parents删除1个元素,则需要在调用splice()时指定要删除的元素数。 Then you can index the value to get that element. 然后,您可以为该值编制索引以获取该元素。

progen1 = parents.splice(n1, 1)[0];

The error message reads: Cannot read property '0' of undefined 错误消息显示: Cannot read property '0' of undefined

Looking at your snippet, I find cromossomo[0] . 看着您的代码片段,我发现cromossomo[0]

If cromossomo is not present in either parents[n1] or progen1 , it is undefined , which leads to the error. 如果cromossomo不存在于parents[n1]progen1 ,则它是undefined ,从而导致错误。

So maybe you have a look at these first and verify each of them has a cromosso . 因此,也许您首先看一下这些,并验证其中每个都有一个cromosso

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM