【问题标题】:How to fetch the length of a string and fetch values?如何获取字符串的长度并获取值?
【发布时间】:2019-03-16 17:07:24
【问题描述】:

如何在 javascript 中获取长度和单个值 这是示例数据

examples:
       "numbers": "248001,248142",
        "numbers": "588801,248742,588869"

Actuall code
        {
            "_id" : ObjectId("579ce69f4be1811f797fbab2"),
            "city" : "",
            "sdescription" : "",
            "categories" : [
                    "5729f312d549cc3212c8393b"
            ],
            "numbers" : "4555855,421201",
            "createdAt" : ISODate("2016-07-30T17:40:47.022Z"),
            "month" : 7,
            "year" : 2016    
    }
here is my code and error

let num = numbers.split(',')
(node:5628) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function

我尝试使用 split 来分隔值,但有时它会返回错误,因为 number.split 不是函数。

我想返回两件事:

  1. length:在第一个示例中长度应为 2,在第二个示例中 长度应为 3。

2.values 应该被拆分

【问题讨论】:

  • "numbers": "248001,248142" 这是如何存储的?大批 ?字符串?
  • @CodeManiac 已更新,请检查。它在 json 对象内
  • @p.s.w.g 更新请检查
  • 没有。我们需要查看 实际 代码,了解您如何尝试解析此对象。 numbers 来自哪里?该错误表明它不是字符串,因此问题可能是由于您获取该变量的方式。

标签: javascript string split string-length


【解决方案1】:

你需要从对象名objectname.keyname开始调用

var obj = { "city": "", "sdescription": "", "categories": [ "5729f312d549cc3212c8393b" ], "numbers": "4555855,421201", "month": 7, "year": 2016 }
var res = obj.numbers.split(',').length;
console.log(res)

【讨论】:

  • 但有时它会返回(node:16568) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function
【解决方案2】:

您可以遍历您的对象,然后为每个元素访问 numbers 属性,然后访问 split 并查找长度

let json = [{"numbers": "248001,248142"},{"numbers": "588801,248742,588869"},{"numbers":[]}]

json.forEach(({numbers})=>{
  console.log(typeof numbers === 'string' ? numbers.split(',').length : 'Not a string')
})

【讨论】:

  • 但有时它会返回(node:16568) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function
  • @Schüler 您可以检查numbers 的第一种类型,然后使用拆分,检查更新
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多