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/