JavaScript函数不返回输出。不确定我的变量是否在正确的位置

时间:2017-05-19 15:53:05

标签: javascript variables scope

不确定为什么这没有输出。这应该返回6但它没有返回任何东西。我究竟做错了什么?



var stock_prices = [10, 7, 5, 8, 11, 9]

function getMaxProfit(stock_prices){
  var current_price = stock_prices[0]
  var min_price = current_price
  var max_profit = 0
  var current_profit = 0
  for (var i = 0; i < stock_prices.length; i++){
    if (current_price < min_price){
      min_price = current_price
      current_profit = current_price - min_price
      if (current_profit > max_profit){
        max_profit = current_profit
      }
    }
  }
  return max_profit
}

console.log(getMaxProfit(stock_prices))
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

因此,根据您提供的内容,我认为您希望获得阵列中最高和最低数字之间的差异(您称之为“利润”),因为您希望它返回6。

以下代码执行此操作并返回先前所述的值:

# Hive metastore 1
sc1 = SparkContext()
hiveContext1 = HiveContext(sc1)
hiveContext1.setConf("hive.metastore.warehouse.dir", "tmp/Metastore1")

#Hive metastore 2
sc2 = SparkContext()
hiveContext2 = HiveContext(sc2)
hiveContext2.setConf("hive.metastore.warehouse.dir", "tmp/Metastore2")

#Reading from a table presnt in metastore1
df_extract = hiveContext1.sql("select * from emp where emp_id =1")

# Need to write the result into a different dataframe
df_extract.saveAsTable('targetdbname.target_table',mode='append',path='maprfs:///abc/datapath...')

答案 1 :(得分:0)

在循环过程中,您缺少增加current_price的值。这将始终打印您的ans 0.因为它检查10&gt; 10,它是假的所以它给你0输出并且迭代继续进行但是current_price仍然是stock_prices [0] = 10.所以在i&lt; 6,它出现循环并打印0作为你的ans。所以循环后设置current_price = stock_price [i]。这允许更改current_price的值。如果有任何混淆,请发表评论。