TypeError: Cannot read property 'MyProperty' of undefined

TypeError: Cannot read property 'MyProperty' of undefined

我有一个对象对数组,如下所示:

0: pairs {_stim1: {img: "images/F111C.png", gender: 0, rating: "3"}, _stim2: {img: "images/F042C.png", gender: 0, rating: "3"}}
1: pairs {_stim1: {…}, _stim2: {…}}
2: pairs {_stim1: {…}, _stim2: {…}}
3: pairs {_stim1: {…}, _stim2: {…}}
4: pairs {_stim1: {…}, _stim2: {…}}
5: pairs {_stim1: {…}, _stim2: {…}}
6: pairs {_stim1: {…}, _stim2: {…}}
7: pairs {_stim1: {…}, _stim2: {…}}

我正在尝试将阵列减少到 6 对,并且每个性别尽可能接近 3 对 属性(1 或 0)。为此,我有一个笨拙的解决方案,在该解决方案中,我遍历列表并将性别为 0 的 3 对对象添加到列表中,然后添加性别为 1 的 3 对对象,如下所示:

pair_count = 0;
if ((stim_pairs.length > 6)) {
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 3)) {
            if ((i.stim1.gender === 0)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 6)) {
            if ((i.stim1.gender === 1)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
}

但是,我 'i.stim1' 和 'i.stim2' returns 'undefined'... 我得到了这个错误:

'无法读取未定义的 属性 'gender''

我做错了什么?

你可以验证 i.stim1.gender 属性 是否存在

if(typeof i.stim1.gender !== 'undefined'){ //your code here}

我已经解决了您的代码中的错误,因此它可以正常工作,但您不会从中得到正确的答案。最初的问题是它应该是 i._stim1.gender 而不是 i.stim1.gender。之后缺少一些声明,请确保使用调试器和 运行 控制台上的此代码以了解问题。

var pair_count = 0,
initial_stim_pairs = [],
final_stim_pairs = [];
if ((stim_pairs.length > 6)) {
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c ++) {
        i = _pj_a[_pj_c];
debugger;
        if ((pair_count < 3)) {
            if ((i._stim1.gender === 0)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
    for (var i, _pj_c = 0, _pj_a = stim_pairs, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
        i = _pj_a[_pj_c];
        if ((pair_count < 6)) {
            if ((i._stim1.gender === 1)) {
                initial_stim_pairs.push(i);
                final_stim_pairs.push(i);
                pair_count += 1;
            }
        }
    }
}