Assemblyscript: Array#splice 不能添加元素

创建于 2020-10-12  ·  5评论  ·  资料来源: AssemblyScript/assemblyscript

在普通 JavaScript 中:

fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
fruits // == ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]

但仅在 AS 中签名:

function splice(start: i32, deleteCount?: i32): Array<T>

还有其他方法可以将数据拼接到现有数组中吗?

question

所有5条评论

目前 AS 不能执行可变参数函数。 因此,我建议使用此解决方法来插入新项目:

export function insertAfter<T>(arr: T[], index: i32, value: T): T[] {
  const len = arr.length + 1
  const res = new Array<T>(len)
  if (index < 0) index = len + index - 1
  if (index > len) index = len - 1
  let i = 0
  while (i < index) res[i] = arr[i++] // or use memory.copy
  res[i++] = value
  while (i < len) res[i] = arr[i++ - 1] // or use memory.copy
  return res
}

// intead fruits.splice(2, 0, "Lemon", "Kiwi") use:
fruits = insertAfter(fruits, 2, "Lemon");
fruits = insertAfter(fruits, 3, "Kiwi");

@MaxGraey你认为我们可以在 stdlib 中同时提供这个吗? 就像spliceAndInsert使用数组而不是其余参数一样?

我不认为插入项数组是正确的解决方案。 无论如何,我们还有很多其他地方需要可变参数函数,因此最好在编译器中为此添加适当的机制。

非常感谢@MaxGraey

insertAfter工作方式与宣传的有点不同,它不是就地数组替换,而是每次都分配一个新数组(例如,不在内部使用realloc ),因此需要重新分配:

import {insertAfter} from "./insertAfter";

export function example(): string[] {
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits = insertAfter(fruits, 2, "Lemon");
    fruits = insertAfter(fruits, 3, "Kiwi");
    return fruits;
}

在浏览器中(使用修改后的 Loader 脚本导出getArraygetString ):

fruits_ptr = assemblyscript.module.exports.example()
// 21359280
fruits = Loader.getArray(fruits_ptr)
// (6) [1152, 1184, 1312, 1616, 1216, 1248]
fruits.map(Loader.getString)
// (6) ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]

image

是的,固定的例子。 顺便说一句,您可以使用__reallocmemory.copy改进它

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

kyegupov picture kyegupov  ·  3评论

jerrywdlee picture jerrywdlee  ·  4评论

DanielMazurkiewicz picture DanielMazurkiewicz  ·  4评论

drachehavoc picture drachehavoc  ·  6评论

evgenykuzyakov picture evgenykuzyakov  ·  3评论