vue.js 使用Javascript删除数组的第一个元素时出现问题

vmjh9lq9  于 2023-06-06  发布在  Vue.js
关注(0)|答案(1)|浏览(198)

我试图在数组中找到一个元素,如果找到了,删除该元素,然后将该元素添加到数组的开头。
但是,当我记录数组sortedAdv时,由于某种原因,它只返回一个元素长度
我的代码:

let advantages = [ 'liked', 'sendUnlimitedLikes', 'unlockSundays', 'getBoosted', 'filters', 'revealAllProfiles', 'wholeCountry', 'exlusiveBlogs' ];
 
console.log('advantages', advantages.length);

let index = advantages.findIndex((advantage) => advantage == type);
if (index > -1) {
  console.log('index', index);
  let sortedAdv = advantages.splice(index, 1);
  console.log('sortedAdv', sortedAdv.length);
  sortedAdv.unshift(type);
  console.log('sortedAdv', sortedAdv.length);
  this.setPurchaseAdvantages(sortedAdv);
}
fdbelqdn

fdbelqdn1#

你得到一个数组当你使用这个

let removedElement = advantages.splice(index, 1);
let advantages = ['liked', 'sendUnlimitedLikes', 'unlockSundays', 'getBoosted', 'filters', 'revealAllProfiles', 'wholeCountry', 'exlusiveBlogs'];
let type = 'getBoosted'; 
let index = advantages.indexOf(type); // Find the index of the element
if (index > -1) {
  let removedElement = advantages.splice(index, 1)[0]; // Remove the element and store it
  advantages.unshift(removedElement); // Add the element to the start of the array
}

console.log(advantages);

相关问题