You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用shuffle-array npm模块打乱对象数组报错的排查与替代方案

问题原因分析

你遇到的TypeError: Object(...) is not a function错误,几乎可以肯定是模块导入方式不正确导致的。shuffle-array包采用的是默认导出(而非命名导出),如果你的导入写法不符合它的导出规则,就会让shuffle变成一个非函数类型的对象,从而触发这个错误。

正确的导入与使用方式

根据你的运行环境,选择对应的导入写法即可解决问题:

1. CommonJS环境(比如Node.js项目)

// 正确导入
const shuffle = require('shuffle-array');

let posts = [
  { postUrl: "https://www.linkedin.com/1", action: "Post", profileUrl: "https://www.linkedin.com/company/1", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/2", action: "Post", profileUrl: "https://www.linkedin.com/company/2", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/3", action: "Post", profileUrl: "https://www.linkedin.com/company/3", timestamp: "2019-10-09T09:40:05.356Z" },
];

posts = shuffle(posts);
console.log(posts); // 输出打乱后的数组

2. ES模块环境(比如React、Vite、Vue等现代前端项目)

// 正确导入
import shuffle from 'shuffle-array';

let posts = [
  { postUrl: "https://www.linkedin.com/1", action: "Post", profileUrl: "https://www.linkedin.com/company/1", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/2", action: "Post", profileUrl: "https://www.linkedin.com/company/2", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/3", action: "Post", profileUrl: "https://www.linkedin.com/company/3", timestamp: "2019-10-09T09:40:05.356Z" },
];

posts = shuffle(posts);
console.log(posts); // 输出打乱后的数组
不依赖第三方库的原生解决方案:Fisher-Yates洗牌算法

如果不想依赖外部包,推荐使用经典的Fisher-Yates洗牌算法,它是无偏且高效的,能保证每个元素被打乱到任意位置的概率完全相等:

function shuffleArray(array) {
  // 复制原数组避免直接修改原数据(可选,根据你的需求调整)
  const shuffledArray = [...array];
  
  for (let i = shuffledArray.length - 1; i > 0; i--) {
    // 生成0到i之间的随机索引
    const randomIndex = Math.floor(Math.random() * (i + 1));
    // 交换当前元素和随机索引的元素
    [shuffledArray[i], shuffledArray[randomIndex]] = [shuffledArray[randomIndex], shuffledArray[i]];
  }
  
  return shuffledArray;
}

// 使用示例
let posts = [
  { postUrl: "https://www.linkedin.com/1", action: "Post", profileUrl: "https://www.linkedin.com/company/1", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/2", action: "Post", profileUrl: "https://www.linkedin.com/company/2", timestamp: "2019-10-09T09:40:05.356Z" },
  { postUrl: "https://www.linkedin.com/3", action: "Post", profileUrl: "https://www.linkedin.com/company/3", timestamp: "2019-10-09T09:40:05.356Z" },
];

posts = shuffleArray(posts);
console.log(posts); // 输出打乱后的数组

这个算法的时间复杂度是O(n),空间复杂度如果复制数组则为O(n),直接修改原数组则为O(1),性能表现非常出色。

内容的提问来源于stack exchange,提问作者BennKingy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:22