簡體   English   中英

Typescript Arrays

[英]Typescript Arrays

我正在學習一些 Typescript 並且我將我學到的一切都放在一個頁面中我一直遇到這個錯誤,稱為

類型 'string[]' 不可分配給類型 'string'.ts(2322)

但它仍然在 liveserver LiveServer上顯示陣列

這會影響代碼還是我可以忽略?

這是我的代碼


let description: string= `This TypeScript string can 
span multiple 
lines
`;

let firstName: string = "Testing";
let title: string = "This is a testing page"
let profile: string = `I'm ${firstName}. 
${title}`;

console.log(profile);

let testArray: string[];

testArray=['Typescript','Gaming','Javascript','Python'];
console.log(testingArray);

let heading = document.createElement('h1');
heading.textContent = message;
let body = document.createElement('h2');
body.textContent = description;
let Name = document.createElement('h5');
Name.textContent = profile;
let testingArray = document.createElement('h5');
testingArray.textContent = testArray;
document.body.appendChild(heading);
document.body.appendChild(body);
document.body.appendChild(Name);
document.body.appendChild(testingArray); ```

textContent的類型是一個string ,並且您正在存儲一個字符串數組。 所以錯誤是對的。 您需要使用 join 等方法將數組轉換為字符串。

testingArray.textContent = testArray.join();

或者通過循環數組來創建多個 textContent,根據您的邏輯進行任何操作。

document.body.appendChild(heading);
document.body.appendChild(body);
document.body.appendChild(Name);
for(let testEle of testArray) {
    let testingArray = document.createElement('h5');
    testingArray.textContent = testEle;
    document.body.appendChild(testingArray);
}

這會影響代碼還是我可以忽略?

好吧,我想說不要忽略,因為忽略並沒有幫助我在StackBlitz等其他實時服務器中成功運行它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM