javaScript 数组中用于模式匹配的占位符

javaScript placeholder in array for pattern match

我有一个这样的 js 数组:

let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]

我想做一些模式匹配,这是我的代码:

switch (data){
    case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
        console.log("successfully!")
}

我不关心points数组,但是在js中不存在占位符“_”,其实我知道其他方法可以做到这一点,但是如果我们只使用switch-case,是否可以解决?

我是js新手,有大佬知道怎么做吗?

尝试

switch (data.status){
    case "stay":
    case "move":
        console.log("successfully!")
        break;
}

文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

如果我正确理解您的尝试,您可以尝试将数组缩减为字符串,然后在 switch 语句中使用该字符串。像这样:

var actionString = ""

data.forEach(function(datum) {
    actionString += datum.status + ' ';
});

// Remove extra space at the end
actionString.trim();

console.log(actionString); // "move stay move"

那么你的 switch 语句将是:

switch(actionString) {
    case "move stay move":
        console.log('success!');
        break;
    case "stay move stay":
        console.log('failure?');
        break;
    /* etc */
}