javascript - How to make and object find its own index in an array?
问题描述
I have a simple array of objects with a id
property and I need the ids to be equal to their index. I tried this
var arr = [
{
id: arr.indexOf(this),
length: this.length
},
{
id: arr.indexOf(this),
length: this.length
},
{
id: arr.indexOf(this),
length: this.length
}
]
But that doesn't work. Do I have to use a function outside the array to do this? None of the built in methods would help?
解决方案
// If this.length =3
var arr = [
{length: 3},
{length: 3},
{length: 3}
]
arr.forEach((item, index)=> item.id =index)
console.log(arr)
推荐阅读
- excel - RK4 VBA 函数的难点。函数只返回#REF!价值
- java - 商店 ImageButton 解锁
- regex - 如何将字符串与双破折号和/或单破折号匹配?
- amazon-web-services - 解决不同环境的 AWS SG 自我参考
- php - 如何在 codigniter 中使用 ajax 上传文件
- neo4j - 如何通过 Cypher 中的 CSV 文件为同一节点添加更多属性?
- rust - 如何习惯性地从 Option 转换
导致 ? - python - 如何从字符串的开头和结尾删除字符,而不是从中间删除?
- tensorflow - 二元逻辑回归 - 我们需要 one_hot 编码标签吗?
- vue.js - 在 vue 中使用道具设置默认地图居中