在对象中存储多个数组?

时间:2018-03-14 23:49:42

标签: javascript html

过去,我创建了一个函数,以获取多个Node列表的属性。然后,用属性创建视觉效果。它看起来像这样:

var elem, celElem, elemTop = [],
  elemMag = [],
  elemBot = [],
  elemCent = [],
  winTop, winMag, winBot, winCent, i, x, len, elemCsokk = [],
  elemNo = [],
  elemCentValt = [],
  elemCentWinCent = [];

function getElem(el, cEl, fn) {
  if (el.length === undefined) {
    el = [el];
    cEl = [cEl];
  }
  elem = el;
  celElem = cEl;
  winTop = window.pageYOffset;
  winMag = window.innerHeight;
  winBot = winTop + winMag;
  winCent = winTop + (winMag / 2);
  for (i = 0, len = elem.length; i < len; i++) {
    elemTop[i] = 0;
    elemMag[i] = elem[i].offsetHeight;
    elemBot[i] = 0;
    elemCent[i] = 0;
    elemCsokk[i] = 0;
    topMag(elem[i]);
    fn(i);
  }

}

function topMag(y) {
  x = y;
  do {
    elemTop[i] += x.offsetTop;
    x = x.offsetParent;
  }
  while (x !== document.body);
  x = y;

  elemBot[i] = elemTop[i] + elemMag[i];
  elemCent[i] = elemTop[i] + (elemMag[i] / 2);
  elemCsokk[i] = (elemBot[i] - winTop) / winMag;

}

function opaCsokk(i) {
  elem[i].style.opacity = elemCsokk[i];
}

var element = document.querySelectorAll("div")

window.onscroll = function() {
  getElem(element, element, opaCsokk)
}

该功能非常有效,唯一的问题是,每次滚动发生时执行该功能都会导致性能问题。所以我决定重新考虑这个功能。我需要在每个滚动上获得的是窗口(winTop, winMag, winCent, winBot)的属性。元素的属性没有变化。我在想的是我可以创建一个大数组(替换getElem函数),存储节点列表及其属性。通过这种方式,上面的示例如下所示(获取节点列表中第一个节点的elemMag): bigArray[0]["elemMag"][0] 功能:

var bigArray = [];

function addingToBigArray(elem) {
  var element = elem;
  for (var i = 0; i < element.length; i++) {
    bigArray[bigArray.length] = {
      elemMag[i]: element.offsetHeight,
      elemTop[i]: element.offsetTop
    }
  }
}

但不幸的是,对象的属性不能是数组。如何解决这个问题,使用函数getElem获得上述示例的相同结果?

1 个答案:

答案 0 :(得分:2)

var bigArray = [];

function addingToBigArray(elem) {
  var element = elem;
  for (var i = 0; i < element.length; i++) {
    bigArray[bigArray.length] = {
      [elemMag[i]]: element.offsetHeight
    }
  }
}

请参阅:[]