簡體   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