如何获取字符串的长度并获取值?

时间:2019-03-16 17:07:25

标签: javascript string split string-length

如何在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应该分开

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以遍历对象,然后为每个元素访问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')
})