繁体   English   中英

将两个数组与HTML元素匹配

[英]Matching two arrays with HTML elements

我只在两个数组中的HTML匹配时才尝试运行一个函数。 尝试将数组更改为toString()会将数组中的HTML更改为“ Object HTMLElement”,这是行不通的。 使用array.outerHTML()会返回与array.val()相同的错误。 我宁愿不做double for循环,但我什至尝试了一下,仍然一无所获。 这应该很简单,我想念什么?

上下文:我正在尝试制作西蒙游戏http://codepen.io/zjmitche/pen/MpWzop?editors=1010

//array content in console
var arrayOne = [section#three.square4, section#one.square4, section#three.square4, section#three.square4]
var arrayTwo = [section#three.square4, section#one.square4, section#three.square4, section#two.square4]

function nextCount() {
  if (arrayOne === arrayTwo) {
    //do something
  {
}

尝试循环:

for (var i = 0; i < arrayOne.length; i++) {
  for (var j = 0; j < arrayTwo.length; j++) {
    if (arrayOne[i] != arrayTwo[j]) {
      alert("test")
      arraysMatch = false;
    }
  }
}

好吧,对于初学者来说,您只需要一个循环,因为如果长度不同,它们显然将不匹配。 然后,使用JSON.stringify轻松比较复杂值:

arraysMatch = true;

if (arrayOne.length !== arrayTwo.length) {
  arraysMatch = false;
} else {
  for (var i = 0; i < arrayOne.length; i++) {
    // Use JSON.stringify to get deterministic strings of non-primitives 
    var currVal1 = JSON.stringify(arrayOne[i]);
    var currVal2 = JSON.stringigy(arraytwo[i]);
    if (currVal1 !== currVal2) {
      arraysMatch = false;
      break; // No reason to keep going through the loop any more
    }
  }
}

暂无
暂无

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

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