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

如何在JavaScript中创建键数与数组一致且值为true的对象

如何创建键数量与数组长度一致、值全为true的对象

给定任意数组,我们需要生成一个对象:对象的键是从0开始的连续数字,键的总数等于原数组的长度,每个键对应的值均为true。比如数组长度为2时输出{0:true,1:true},长度为3时输出{0:true,1:true,2:true}。

下面提供几种实用的JavaScript实现方式:

方法1:使用Array.from() + Object.fromEntries()(简洁写法)

这种方式利用数组的映射和对象转换API,一行核心代码就能完成需求:

const createTrueObj = (arr) => {
  return Object.fromEntries(Array.from({ length: arr.length }, (_, idx) => [idx, true]));
};

// 示例调用
const myCar = [{name: 'ford', type: 'A'}, {name: 'opel', type: 'B'}];
console.log(createTrueObj(myCar)); // 输出 {0: true, 1: true}
  • Array.from({ length: arr.length }) 创建一个与原数组长度相同的空数组
  • 第二个参数作为映射函数,将每个数组索引和true组成键值对数组
  • Object.fromEntries() 将键值对数组直接转换为目标对象

方法2:使用for循环(直观易懂)

如果需要更直观的逻辑展示,普通for循环是最容易理解的方式:

const createTrueObj = (arr) => {
  const result = {};
  for (let i = 0; i < arr.length; i++) {
    result[i] = true;
  }
  return result;
};

// 示例调用
const myCar = [{name: 'ford', type: 'A'}, {name: 'opel', type: 'B'}];
console.log(createTrueObj(myCar)); // 输出 {0: true, 1: true}

通过遍历从0到arr.length-1的索引,逐个给对象的对应键赋值true。

方法3:使用Array.keys() + Object.fromEntries()

利用数组自身的索引迭代器来实现:

const createTrueObj = (arr) => {
  return Object.fromEntries(Array.from(arr.keys(), key => [key, true]));
};

// 示例调用
const myCar = [{name: 'ford', type: 'A'}, {name: 'opel', type: 'B'}];
console.log(createTrueObj(myCar)); // 输出 {0: true, 1: true}
  • arr.keys() 获取原数组的索引迭代器
  • 转换为数组后映射成键值对数组,再通过Object.fromEntries()转为目标对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:01:10