Coding - 碼農筆記 / JavaScript

JavaScript – Array裡 some的運用

Array.prototype.some()

some() 方法测试数组中的某些元素是否通过由提供的函数实现的测试。返回值為true 或false

var items = [1,2,3,4,5];
var hasThree = items.some(x => (x === 2)); // 有包含2,返回true
console.log(hasThree);

 

some的運用

<div class="task-list"></div>
var tasks = [
  {
    title: 'Do laundry',
    completed: true
  },
  {
    title: 'Feed the cat',
    completed: true
  },
  {
    title: 'Watch the array lessons on egghead.io',
    completed: true
  },
];

var list = document.querySelector('.task-list');

// 替ul加上class
list.classList.add(
  tasks.some(task => task.completed === false) // 在tasks的array的completed中是否都不等於false
    ? 'task-list--uncompleted' // 是,加 task-list--uncompleted
    : 'task-list-completed' // 否,加 task-list-completed
);


list.innerHTML = tasks
  .map(x => x.completed ? `<s>${x.title}</s>` : x.title)
  .map(x => `<li>${x}</li>`)
  .join('');

 

運用:判斷如果todoList 裡新增的項目已包含在原todoList裡則不新增

var tasks = [
  {
    title: 'Do laundry',
    completed: true
  },
  {
    title: 'Feed the cat',
    completed: true
  },
  {
    title: 'Watch the array lessons on egghead.io',
    completed: true
  },
];


function addTask(title) {
  // 如果新增的title跟列表裡的title相同(some回傳true),則不新增
  if(tasks.some(task => task.title === title)) {
    return;
  }
  tasks.push({title: title, completed: false}) // 如果新增的title跟列表裡的title不相同(some回傳false),則push新增
};

addTask('Feed the cat');
console.log(tasks);

 

參考MDN

© 2024 胡同筆記 | WordPress Theme: Cosimo by CrestaProject.