繁体   English   中英

javascript检查值是否为日期或非数字字符串以停止重新格式化功能

[英]javascript check if value is date or nonnumerical string to stop reformatting function

相当新的javascript用户:

我如何更改此javascript if语句,该语句应针对围绕值转换代码块包装的datesstrings返回FALSE 在下面的应用程序中,它应使值转换为科学计数法,同时不更改日期和名称变量。

  return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));

附加信息:完全使用Unicode减号代替听到的常规破折号,因此我已经尝试在代码中的某处使用.replace(/\\\–|\\\—|\\\−/g, '-')) ,但没有成功。

补充说明:我正在R闪亮的绘图工作中构建一些javascript,以操纵绘图轴上的刻度,但是在使代码处理某些值时遇到了一些问题。

目标:将POS和NEG值转换为科学注释不要转换日期不要转换文本值(或因数)因此严格转换数字

使用此行可在以下演示应用中的y轴上转换pos和neg值:

if(parseInt(d.text) !== 0)

也使得日期(绘制乱七八糟x = ~Date在下面的应用程序),或名称(标绘x = rownames(x)在下面的应用程序。

我尝试使用在SO某处找到的javascript代码检查数字,但是效果不理想。

即将上一行更改为此:

if(parseInt(d.text) !== 0 && isNumber(parseInt(d.text)))

我的APP

library(shiny)
library(plotly)
library(shinythemes)
library(dplyr)
library(png)

ui <- fluidPage(

  plotlyOutput('plotly'),
  br(),
  actionButton(inputId = 'Saveplot', label = icon('floppy-o'), style = "height:40px; width:40px; border-radius: 6px; border-width:3px; border-color:#339fff; 
              color: #339fff; background-color:#fff; font-size:1.4em")
)

server <- function(input, output){
mtcars2 <- mtcars
mtcars2$mpg <- mtcars2$mpg *-1
mtcarsBig <-rbindlist(list(mtcars, mtcars2))
mtcarsBig$Date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 96)

mtcarsBig $ gear <-as.factor(mtcarsBig $ gear)mtcarsBig $ brand <-rep(c('Honda','BMW','Audi','Volvo'),8)

  javascript <- "
  function(el, x) 
  {
    function isNumber(n) {
      return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
    }
    function fixTicks()
    {
      ticks = Plotly.d3.selectAll('g.yaxislayer-above,g.xaxislayer-above').selectAll('text');
      ticks.each(function(d) 
      {
        if(parseInt(d.text) !== 0 && isNumber(parseInt(d.text)))
        {
var num = parseInt(d.text.replace(/\\u2013|\\u2014|\\u2212/g, '-')).toExponential(2);
          Plotly.d3.select(this).text(num);
        }
      })
    }
    el.on('plotly_afterplot', fixTicks);
  }"


  output$plotly <- renderPlotly({
    p <- mtcarsBig %>% 
      split(mtcarsBig$cyl) %>% 
      purrr::map(., function(x) {
        plot_ly(data = x, 
                x = ~Date, 
                y = ~mpg, 
                type = "bar") %>%
          layout( )
      }) %>% 
      subplot(nrows = 3, margin = 0.03)


    p$elementId <- NULL   ## to surpress warning of widgetid
    p <- onRender(p, javascript)
    p
  })
}
shinyApp(ui = ui, server = server)

jQuery有一个很好的函数isNumeric用于检查变量是否为数字,如果是字符串则可能在强制之后。

尝试

if($.isNumeric(d.text) && parseInt(d.text) !== 0)

暂无
暂无

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

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