简体   繁体   English

了解 Javascript Object 和未定义

[英]Understanding Javascript Object and Undefined

I am trying to fix a Wordpress plugin that is no longer supported.我正在尝试修复不再受支持的 Wordpress 插件。 I have narrowed down the error.我已经缩小了错误的范围。 The following line is the problem:以下行是问题:

i[C][0];我[C][0];

It is returning undefined in the function below:它在下面的 function 中返回未定义:

`function S(i) {
        var C,
            P = i.length,
            E = [];
            
      for (C = 0; C < P; C++) {
      console.log(i[C]);
      console.log( JSON.stringify(i[C], null, 2) ); 
      E[C] = i[C][0].offsetTop;
      }
        return E;
    }`

I logged i[C] and have the following result:我记录了 i[C] 并得到以下结果:

从控制台

"length": 0, "prevObject": { "0": {}, "length": 1, "prevObject": { "0": {}, "1": {}, "2": {}, "3": {}, "4": {}, "5": { "jQuery351075030630793491351": { "display": "" } }, "length": 6, "prevObject": { "0": {}, "length": 1, "prevObject": { "0": {}, "length": 1, "prevObject": { "0": {}, "length": 1 } } } } } } “长度”:0,“prevObject”:{“0”:{},“长度”:1,“prevObject”:{“0”:{},“1”:{},“2”:{}, "3": {}, "4": {}, "5": { "jQuery351075030630793491351": { "display": "" } }, "length": 6, "prevObject": { "0": {} , "length": 1, "prevObject": { "0": {}, "length": 1, "prevObject": { "0": {}, "length": 1 } } } } }

Here is a link to the page: https://wolseleyfamilyplace.com/events/这是该页面的链接: https://wolseleyfamilyplace.com/events/

Another note, P is equal to 5.另请注意,P 等于 5。

I am not that familiar with Javascript and reading the objects.我对 Javascript 和阅读对象不太熟悉。 Why is the i[C][0] returning undefined?为什么 i[C][0] 返回未定义? Can it be fixed?可以修复吗?

Maybe it was expecting i to be a jQuery object... And now what is passed to the function is a DOM element.也许它期望i成为 jQuery object ......现在传递给 function 的是一个 DOM 元素。

Try to just remove [0] from E[C] = i[C][0].offsetTop;尝试从E[C] = i[C][0].offsetTop;中删除[0] It all works fine, that was it!一切正常,就是这样!


To just be fullproof... In case both DOM and jQuery object can be passed to the function, you could do:为了完全证明......如果DOM和jQuery object可以传递给function,你可以这样做:

E[C] = i[C][0]? i[C][0].offsetTop: i[C].offsetTop
jQuery--^ DOM--^ jQuery--^ DOM--^

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

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