javascript - 为什么重复元素返回未定义?

标签 javascript arrays loops web-applications

 const cardChild = document.querySelectorAll('.card i');
 const cardsArray = ['a','a','b','b','c','c']; 
 const matchArray = [];

function cardsToClass() {
     for (i = 0; i < cardChild.length; i++) {

         let newCard = cardsArray.pop();
         let newCardClass = cardChild[i];
         matchArray.push(cardsArray[i]);

         newCardClass.className += newCard;
         console.log(cardsArray);
     }; }

您好!此函数使用 .pop() 将 cardsArray 元素作为 DOM 元素中的类“弹出”。我的最终结果需要是两个相同的数组(cardsArray 和 matchArray)。我已经接近了。但是,当我 console.log matchArray 它返回:

 ['a','b','c',undefined,undefined,undefined]

我认为发生了一些事情

 matchArray.push(cardsArray[i]);

但不确定。有谁知道为什么它不返回重复元素?

谢谢!

最佳答案

您正在将数组从第一个位置复制到最后一个位置。 但是,通过添加 pop(),您每次使用 pop 时也会删除最后一项,因此有一半的数组结尾未定义。

pop 替换为 unshift() 这将解决您的问题。

我不太明白代码的目的,但 html 可能会帮助我添加它。

希望这有帮助:>

//const cardChild = document.querySelectorAll('.card i');
 const cardsArray = ['a','a','b','b','c','c']; 
 const matchArray = [];

function cardsToClass() {
     for (i = 0; i < cardsArray.length; i++) {

         let newCard = cardsArray.unshift();
         //let newCardClass = cardChild[i];
         matchArray.push(cardsArray[i]);

         //newCardClass.className += newCard;

     };
console.log(cardsArray);
console.log(matchArray);
}
     
cardsToClass() 

关于javascript - 为什么重复元素返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51291603/

相关文章:

javascript - 使用map返回空数组而不是[0]零

python - C++ 中是否有相当于 "for ... else"Python 循环的方法?

c - 声明一个结构数组

Javascript - 动态从数组中获取元素

c++ - 使用指向二维数组的一维指针数组?

r - 编写嵌套 for 循环以连接 R 中数据帧中共享键的行

java - ReplaceAll 和循环?

javascript - 自定义指令中的 ngRepeat - 插值

javascript - 是否根据定义调用匿名函数?

javascript - 当我删除并重新附加表单元素时,如何防止表单输入数据被重置?