【问题标题】:How to slice by index object property value which is a string?如何按字符串的索引对象属性值切片?
【发布时间】:2020-03-22 15:19:07
【问题描述】:

我有一个对象:

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

我需要按索引分割content 属性的值,例如,如果我有index = 4,那么应该打印console.log(text.content)

“一些”

看起来这段代码不起作用:

text.content.slice(0, index);

我还有

“一些文字”

console.log(text.content)

我误解了什么?

【问题讨论】:

  • 使用text.content.substr(0, index); 代替切片。
  • 一些数组运算符适用于字符串,但不是全部。使用 substr
  • @SajeebAhamed, substr 已弃用 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 。推荐使用substring。谢谢!
  • 谢谢。是我的错。我只是想使用子字符串。
  • @SajeebAhamed,我刚刚尝试将splice 替换为substring,但它仍然不起作用。但我使用 vue,所以它也可能是 vue 反应性的问题。

标签: javascript slice


【解决方案1】:

字符串是不可变的。您需要使用新的子字符串对属性进行赋值。

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

console.log(text.content);

【讨论】:

  • 我完成了任务,但没有成功。我也使用 vue,这可能是 vue 反应性的问题。
【解决方案2】:

看看 string.substring():

https://devdocs.io/javascript/global_objects/string/substring

你去吧:

text.content.substring(0, index)

【讨论】:

  • 它现在可以与slice 一起使用,但可以使用分配。感谢您指出 slice 的另一个选项。
【解决方案3】:

Slice 不会改变字符串。因此,如果您改为使用 console.log(text.content.slice(0, index)),您将看到您正在寻找的结果。

【讨论】:

  • 您对Slice doesn't mutate the string 的看法是正确的。谢谢!
【解决方案4】:

strings are immutable。您需要将sliced 值分配回content

const text = {
    type: 'text',
    content: "some text",
};
const index=4;
text.content=text.content.slice(0,index)
console.log(text)

slice 工作正常

【讨论】:

  • 我在分配方面犯了一些错误,但对我没有用。现在它起作用了。谢谢!
【解决方案5】:

根据规范 (MDN):

slice() 方法提取字符串的一部分并将其作为 新字符串,不修改原字符串。

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

const index = 4;
const result = text.content.slice(0, index);

console.log(text.content); // some text
console.log(result); // some

text.content = result;
console.log(text.content); // some

【讨论】:

  • 我在分配方面犯了一些错误,但对我没有用。现在它起作用了。谢谢!
猜你喜欢
  • 2016-08-29
  • 2021-11-20
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 2022-06-15
  • 2022-01-16
  • 2019-08-02
  • 2018-12-16
相关资源
最近更新 更多