堆栈ID的数据类型可以是数组或字符串。
在下面的代码中,stack[0].id
是Array
,stack[1].id
是字符串。
问题是当 id 作为数组返回时 stackConfig 未定义。
我如何动态处理这个问题?
let stack = [{id:['stack1','stack2']},{id:'stack2'}]
let stackConfig = this.stackConfigs.find(c => c.id === selectionId);
最佳答案
你可以尝试这样的事情:
let stack = [{id:['stack1','stack3']},{id:'stack2'},{id:'stack4'}]
let selectionId = 'stack2';
let stackConfig = stack.find(c => {
if(Array.isArray(c.id)) { if (c.id.indexOf(selectionId) != -1) return true;}
else { return c.id === selectionId }
return false;
});
console.log(stackConfig);
关于javascript - 在代码中动态处理字符串和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49105894/