首页 > 解决方案 > JavaScript 数组切片似乎清除了其他数组

问题描述

第一版代码

// Creates random string
function randomString() {
  return Math.random().toString(36).substring(7);
}

// Creates dynamic rows for us
const rows = [...Array(16).keys()].map(el => {
  return {
    id: el + 1,
    title: `title-${randomString()}`,
    description: `description-${randomString()}`,
  };
});

// How mmany items per page
const limit = 10;

// Total number of pages that was determined by dividing the number of rows by the limit per page
const page_quantity = Math.ceil(rows.length / limit);

// Slice functionality
const pages = [];

// Array that will store rows for a page
const page = [];

rows.forEach((row, index) => {
  // Will determine we if we have reached the limit
  const is_page = (index + 1) % limit === 0;

  // Push rows to page
  page.push(row);

  // If we have reached the limit push "page" to the pages array
  if (is_page) {
    console.log(page);
    pages.push(page);
    page.splice(0)
  }

  // If we have not reached the limit per page but have reached the end of the array push page to pages
  if (index === rows.length - 1) {
    console.log(page);
    pages.push(page);
    page.splice(0)
  }

});

console.log(pages);

结果 :

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
length: 0
__proto__: Array(0)

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
length: 0
__proto__: Array(0)

(2) [Array(0), Array(0)]
0: []
1: []
length: 2
__proto__: Array(0) 

如果我像这样更改pagelet pages = []page.splice()page = []

// Creates random string
function randomString() {
  return Math.random().toString(36).substring(7);
}

// Creates dynamic rows for us
const rows = [...Array(7).keys()].map(el => {
  return {
    id: el + 1,
    title: `title-${randomString()}`,
    description: `description-${randomString()}`,
  };
});

// How mmany items per page
const limit = 10;

// Total number of pages that was determined by dividing the number of rows by the limit per page
const page_quantity = Math.ceil(rows.length / limit);

// Slice functionality
const pages = [];

// Array that will store rows for a page
let page = [];

rows.forEach((row, index) => {
  // Will determine we if we have reached the limit
  const is_page = (index + 1) % limit === 0;
  console.log((index + 1) % limit === 0);

  // Push rows to page
  page.push(row);

  // If we have reached the limit push "page" to the pages array
  if (is_page) {
    console.log(page);
    pages.push(page);
    page = [];
  }

  // If we have reached the end of the array push elements to page
  if (index === rows.length - 1) {
    pages.push(page);
    page = [];
  }

});

console.log(pages);

我得到了一个包含两个元素的数组的正确结果,一个包含 10 个“行”,另一个包含 6 个“行”。为什么第一个不工作Array.splice

标签: javascript

解决方案


当您调用 Array.splice(0) 时,将返回一个包含原始数组中所有项的新数组,并将原始数组设置为 []。当您推送原始数组时,您正在推送一个指向您正在使用 slice 函数清空的原始数组的指针。

如果您离开,它将按您的预期工作

const page = [];

但更换

pages.push(page);
page = [];

pages.push(page.splice(0));

推荐阅读