文字列であるインデックスオブジェクトのプロパティ値でスライスする方法?

webprogrammer:

私は、オブジェクトを持っています:

const text = {
    type: 'text',
    content: "some text",
};

私はのスライス値必要content私が持っている場合、例えば、インデックスでプロパティをindex = 4、次にconsole.log(text.content)印刷する必要があります:

"いくつか"

このコードは動作しないように見えます:

text.content.slice(0, index);

私はまだ持っています

「いくつかのテキスト」

console.log(text.content)

私は何を誤解していますか?

ニーナショルツ:

文字列は不変です。あなたは新しい部分を持つプロパティへの代入が必要です。

const
    text = { type: 'text', content: "some text" },
    index = 4;
    
text.content = text.content.slice(0, index); // assignment of substring

console.log(text.content);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=347188&siteId=1