Select

select 指令根據其第三個運算元是否為零來選擇其前兩個運算元中的一個。它與許多其他語言中的三元運算子(例如 false ? 10 : 20)有一些相似之處,但它不會 短路。該指令後面可以跟一個即時值型別:select (result T)select (result T) 使用不同的二進位制操作碼,並允許除了 WebAssembly MVP 引入的型別(i32i64f32f64)之外的型別,例如,它允許在兩個 externref 值之間進行選擇。

試一試

(module
  (func (export "select_simple") (result i32)
    ;; load two values onto the stack
    i32.const 10
    i32.const 20

    ;; change to `1` (true) to get the first value (`10`)
    i32.const 0
    select
  )
  (func (export "select_externref") (param $value externref) (param $condition i32) (result externref)
    ;; this is "select t", the explicitly typed variant
    ref.null extern
    local.get $value
    local.get $condition
    select (result externref)
  )
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url)).then((result) => {
  const { select_simple, select_externref } = result.instance.exports;

  console.log(select_simple());
  // Expected output: 20

  // If the second parameter is zero, returns the first parameter (which may be an arbitrary JS value)
  const map = new Map();
  console.log(select_externref(map, 0));
  // Expected output: [object Map]
  console.log(select_externref(map, -1));
  // Expected output: null
});

語法

wat
;; push two values onto the stack
i32.const 10
i32.const 20

;; change to `1` (true) to get the first value (`10`)
i32.const 0
select
f32.const nan
f32.const -54.1

;; change to `1` (true) to get the first value (`nan`)
i32.const 0
select (result f32)
指令 二進位制操作碼
select 0x1b
select t 0x1c