【问题标题】:Splicing Stuff With Js用js拼接东西
【发布时间】:2021-12-08 16:19:35
【问题描述】:

好的,我正在制作一个进化模拟器,他们需要获得食物才能生存。等等等等等等。但是这个接头不起作用,我不知道如何修复它

代码:

function track(blob, ob) {
    for (let i = 0; i < ob.length; i++) {
        const dist = Math.hypot(
            blob.x - ob[i].x, 
            blob.y - ob[i].y
        )

        if (dist - 20 - blob.size < 1) {
            blob.food++
            ob.splice(ob[i], 1)
        } else {
            const angle = Math.atan2(
                ob[i].x - blob.y,
                ob[i].y - blob.x
            )
            const velocity = {
                x: Math.cos(angle) / 2,
                y: Math.sin(angle) / 2
            }
            blob.velocity = velocity
        }
    }
}

【问题讨论】:

  • 它会抛出错误,还是不能按预期工作?
  • 1. ob 是什么? 2. 你预计会发生什么? 3. 会发生什么?
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: javascript array-splice


【解决方案1】:

.splice() 的工作方式是指定起始索引、要删除的项目数以及要在该索引处插入的项目列表。

var array = [3, 4, 5, 6];
array.splice(1, 1);
console.log(array); //[3, 5, 6]
array.splice(2, 0, 7);
console.log(array); //[3, 5, 7, 6]
array.splice(0, 2, 1, 8);
console.log(array); //[1, 8, 5, 7, 6]

Docs

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2010-12-28
    • 2020-12-03
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多