简体   繁体   English

一步将整数转换为字符串和修剪

[英]Convert an Integer to a String and Trim in 1 Step

I'm wondering if it's possible to convert an integer to a string and trim it within one step. 我想知道是否有可能将整数转换为字符串并在一步之内对其进行修整。

I have the following object: 我有以下对象:

currentForm currentForm

{
id:1,
name:"Abusicus",
value:12203,
period:"Morning",
favoriteSnack:"      "
....
}

I need to find a way to check if the values are empty ("") or have something in it. 我需要找到一种方法来检查值是否为空(“”)或其中是否包含某些内容。

Eg. 例如。 favoriteSnack would be considered empty since it's just white space. 最喜欢的零食被认为是空的,因为它只是空白。 Currently I use this to check for white space: 目前,我使用它来检查空白:

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].trim().length);

But this does not work on fields with values that are integers. 但这不适用于整数值的字段。 I want to do something like this: (Convert the integers to strings and then do a check on all the values) 我想做这样的事情:(将整数转换为字符串,然后对所有值进行检查)

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].toString().trim().length);

Is something like this possible? 这样的事情可能吗?

As I see your object is that, an object, not an array, to use every, first I would map all the keys and cast to a string with + '', then check the condition, like this: 如我所见,您的对象是要使用每个对象的对象,而不是数组,首先,我将映射所有键并使用+''转换为字符串,然后检查条件,如下所示:

var validInput = Object.keys(currentForm)
  .map( v => currentForm[v] + '')
  .every( v => v.trim().length);

jsfiddle in action here jsfiddle在这里起作用

Hope this helps. 希望这可以帮助。

For int, value will be 0, and even you convert, it will be "0", not " " Regardless, there is a dirty way to do this by adding "" in front of an int. 对于int,值将为0,即使您进行转换,也将为“ 0”,而不是“”不管怎样,有一种肮脏的方法是在int前面添加“”。 You can do sonething like this: "" + value; 您可以像这样进行监听:“” +值;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM