首页 \ 问答 \ 仅当字符串是数字时,Javascript才将字符串转换为数字(Javascript converting string to number only if the string is an number)

仅当字符串是数字时,Javascript才将字符串转换为数字(Javascript converting string to number only if the string is an number)

如果我不知道字符串值是否为有效数字,如何将字符串转换为数字。 如果它无效,我想保留字符串。

"0" -> 0
"0.5" -> 0.5
"100" -> 100
"abc" -> "abc" //  remains a string
" " -> " " // remains an empty string
"-1" -> -1 // I'd like to convert negative numbers too

我试过了

var str = " ";
var num = +str // num = 0
var num = Number(str) // num = 0
var num = parseInt(str) // num = NaN

所以我的问题似乎是空间问题。 我正在考虑使用parseInt但我认为在Javascript中使用NaN作为值可能是一个坏主意,只是将字符串保留为更好。


How can I convert string to a number if I don't know if the string value is a valid number or not. I want to leave the string as is if it is not valid.

Example

"0" -> 0
"0.5" -> 0.5
"100" -> 100
"abc" -> "abc" //  remains a string
" " -> " " // remains an empty string
"-1" -> -1 // I'd like to convert negative numbers too

I've tried

var str = " ";
var num = +str // num = 0
var num = Number(str) // num = 0
var num = parseInt(str) // num = NaN

So seems my problem is with space. I was thinking of using parseInt but I thought that it might be a bad idea to use NaN as a value in Javascript and just leaving the string as is would be better.


原文:https://stackoverflow.com/questions/44258536
更新时间:2022-04-22 15:04

最满意答案

根据你的部分代码;

1)由于滚动条的默认最大值和最小值分别为1.0和0.0,因此scrollToTop方法不会滚动到顶部。 因为您将滚动条的值设置为0.5,这意味着加载的ListView的“滚动到中心”。

2)在附加eventHandler之后,滚动条将不再移动,因为事件处理程序使用了ScrollEvent 。 scrollBar不会通过鼠标滚轮移动,但会通过鼠标拖动滚动滚动条。

3)我建议使用ListView.scrollTo()方法:

private final EventHandler<ScrollEvent> scrollEventFilter = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent t) {
    if (t.getDeltaY() < 0) {
        getSelectionModel().selectNext();
    } else {
        getSelectionModel().selectPrevious();
    }

    scrollTo(lst.getSelectionModel().getSelectedIndex());

    t.consume();
  }

};


According to your partial codes;

1) Since the default max and min values of scrollbar are 1.0 and 0.0 respectively, the scrollToTop method is not scrolling to top. Because you are setting the scrollbar's value to 0.5 in it, which means "scroll to center" of the loaded ListView.

2) After attaching the eventHandler, the scrollbar will not move any more, because the event handler consuming the ScrollEvent. The scrollBar will not move by mouse wheel, but it will scroll by mouse drag on it.

3) I suggest to use ListView.scrollTo() method as:

private final EventHandler<ScrollEvent> scrollEventFilter = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent t) {
    if (t.getDeltaY() < 0) {
        getSelectionModel().selectNext();
    } else {
        getSelectionModel().selectPrevious();
    }

    scrollTo(lst.getSelectionModel().getSelectedIndex());

    t.consume();
  }

};

相关问答

更多
  • 如果要修改条形的宽度和高度,可以查看此问题 , 该问题指向使用System.Windows.SystemParameters修改这些值的方向。 但是我认为你需要更复杂的样式(例如更改背景),所以我担心你需要使用控件模板部件。 检查这两个链接(在这个问题的答案中找到): 在WPF中设置ScrollViewer / Scrollbar的样式 设置WPF ScrollViewer的样式 If you want to modify the width and height of the bars, you can ...
  • 根据你的部分代码; 1)由于滚动条的默认最大值和最小值分别为1.0和0.0,因此scrollToTop方法不会滚动到顶部。 因为您将滚动条的值设置为0.5,这意味着加载的ListView的“滚动到中心”。 2)在附加eventHandler之后,滚动条将不再移动,因为事件处理程序使用了ScrollEvent 。 scrollBar不会通过鼠标滚轮移动,但会通过鼠标拖动滚动滚动条。 3)我建议使用ListView.scrollTo()方法: private final EventHandler
  • 尝试在布局xml文件中键入 android:scrollbars="none" 教程在这里 http://developer.android.com/reference/android/view/View.html#attr_android:scrollbars 希望,它可以帮助你 Try to type this in layout xml file android:scrollbars="none" Tutorial is here. http://developer.android.com/ref ...
  • 我认为问题源于您在完全声明之前尝试访问paneClicked 。 您可以使用带有this关键字的匿名类来克服此问题: EventHandler paneClicked = new EventHandler() { @Override public void handle(MouseEvent event) { event.consume(); pane.removeEventFilter(MouseEvent. ...
  • 想一想: min , max和value是滚动条的逻辑值。 value范围介于min和max之间,当且仅当滚动条一直向左滚动(或顶部,对于垂直滚动条)时,该value等于min 。 当且仅当滚动条尽可能向右(或底部)滚动时,它等于max。 visibleAmount属性实际上只是一个可视属性,用于确定“拇指”的大小。 这种关系是这样的 thumbSize / trackSize = visibleAmount / (max - min) visibleAmount将影响实际像素和“逻辑单元”之间的关系; ...
  • 我看到3个选项...... 在ListView上手动创建Header作为网格,并隐藏ListView的标题。 重写ListView的ControlTemplate 使用DataGrid而不是ListView 对于#1,您需要在Header的顶部创建一个包含Grid的DockPanel,并且ListView占用剩余空间。 您必须指定每列的宽度以正确排列它们,并确保隐藏ListView标头。 对于#2,您可以使用Expression Blend等工具为ListView添加默认的ControlTemplate,并 ...
  • 您需要在本机控件上设置VerticalScrollBarEnabled ,而不是基于表单的控件: class CustomListView : ListViewRenderer { protected override void OnElementChanged(ElementChangedEventArgs e) { base.OnElementChanged(e); if (Control != null) ...
  • 更改 .list-view .scroll-bar:vertical { -fx-padding: 0px; } 至 .list-view .scroll-bar:vertical { -fx-scale-x: 0; } 如果你想在项目之间禁用移动: listview.setMouseTransparent( true ); listview.setFocusTraversable( false ); Change .list-view .scroll-bar:vertical { ...
  • VerticalScrollBarVisibility不是布尔值。 这是一个枚举,尝试: VerticalScrollBarVisibility="Hidden" VerticalScrollBarVisibility is not a boolean. It's an enum, try: VerticalScrollBarVisibility="Hidden"
  • 这里的问题是父,即GridPane 。 一个GridPane设置layoutX属性本身。 如果更改,在下一个布局脉冲期间, GridPane简单地将Node “移回”它所在的位置。 要使这项工作,您可以使用translateX属性。 translateX属性表示节点应从其布局位置移动的水平距离。 使用这种方法,绑定属性而不是使用侦听器也更容易: label.translateXProperty().bind(scroll.valueProperty()); 或者,您可以使用未自行设置布局位置的父级(如“ ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)