gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:26:48 25 4
gpt4 key购买 nike

我有一个非常简单的问题,但我无法解决它。我想将服务中的数据切碎并将其放入数组中,但无论使用属性还是数组都无法使其达到我想要的效果。

示例文本: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)
});

错误:“string”类型的参数无法分配给“[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)
});

错误:类型错误:无法读取未定义的属性(读取“推送”)

我想要的结果:

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'

最佳答案

首先,您需要初始化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

关于javascript - 在 Typescript 中使用多个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74374476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com