Ionic 在Typescript中使用多个字符串数组

eni9jsuy  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(153)

我有一个非常简单的问题,但是我解决不了,我想把服务中的数据切碎,然后丢到数组中,但是我不能让它成为我想要的,无论是使用属性还是数组。
示例文本: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'
3qpi33ja

3qpi33ja1#

首先,你需要初始化test数组,否则,你就无法推入它。

let test: [string, string][] = [];

test包含大小为2的string元组。将string推入其中将不起作用。您需要构造一个由t6t8组成的元组并将其推入。

test2.forEach((element) => {
  let test3 = element.split("~");
  let t6 = test3[0];
  let t8 = test3[1];
  test.push([t6, t8]);
});

Playground

相关问题