我有一個非常簡單的問題,但我無法解決。我想從服務中切碎資料并將其放入陣列中,但是我不能讓它成為我想要的,既不使用屬性也不使用陣列。
示例文本:abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|
示例代碼:
let exampleText: string = 'abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|'
let test: [string, string][];
let test2 = exampleTest.split('|');
test2.forEach(element => {
let test3 = element.split('~');
let t6 = test3[0]
let t8 = test3[1]
test.push(t6,t8)
});
錯誤:Argument of type 'string' is not assignable to parameter of type '[string, string]'.ts(2345)
另一種方式:
let exampleText: string = 'abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|'
let test: [Pro1:string,Pro2:string];
let test2 = exampleTest.split('|');
test2.forEach(element => {
let test3 = element.split('~');
let t6 = test3[0]
let t8 = test3[1]
test.push(t6,t8)
});
錯誤:TypeError: Cannot read properties of undefined (reading 'push')
我想要的結果:
console.log(test[0][0]) //print 'abc'
console.log(test[0][1]) //print 'sdfgsdg'
console.log(test[1][0]) //print 'def'
console.log(test[1][1]) //print 'dgdfgdf'
或者
console.log(test[0].Pro1) //print 'abc'
console.log(test[0].Pro2) //print 'sdfgsdg'
console.log(test[1].Pro1) //print 'def'
console.log(test[1].Pro2) //print 'dgdfgdf'
uj5u.com熱心網友回復:
首先,您需要初始化test陣列。否則,你無法推入它。
let test: [string, string][] = [];
test包含string大小為 2 的元組。string將 a 推入其中不起作用。您需要構建一個由 and 組成的元組t6并t8推送它。
test2.forEach((element) => {
let test3 = element.split("~");
let t6 = test3[0];
let t8 = test3[1];
test.push([t6, t8]);
});
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/531076.html
